﻿using System;
using System.IO;
using System.Data;
using System.Linq;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Text.RegularExpressions;

using CE.User;
using CE.Global;
using CE.Database;
using CE.Provider;
using CE.CarInsurance;
using CE.Company;
using CE.Mail;
using CE.InputOut;
using System.Net;
using CE.Security;

public partial class car_insurance_trueyou_promo_results : MyLanguageBasePage
{
    string _redirectUrl = "";
    string _strNewEmail = "";
    string _strNewName = "";
    string _strNewMobile = "";
    string _strNewUserId = "";
    string _strUserStatus = "";
    protected override void InitializeCulture()
    {
        String selectedCulture = CE.Global.General.SetCulture();
        base.InitializeCulture();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Master.Page.Title = Resources.Title.QuoteResultsTitle;

        LiteralControl newln = new LiteralControl(Environment.NewLine);
        HtmlMeta language = new HtmlMeta();
        language.Name = "language";
        language.Content = Resources.Title.PageLanguage;

        HtmlMeta keywords = new HtmlMeta();
        keywords.Name = "keywords";
        keywords.Content = Resources.Title.QuoteResultsKeyword;

        HtmlMeta description = new HtmlMeta();
        description.Name = "description";
        description.Content = Resources.Title.QuoteResultsDescription;

        Page.Header.Controls.AddAt(10, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(11, language);
        Page.Header.Controls.AddAt(12, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(13, keywords);
        Page.Header.Controls.AddAt(14, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(15, description);

        if (Session[CE.Global.General.UserId] != null && Session[CE.Global.General.UserTypeId] != null)
        {
            if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) !=
                Convert.ToInt32(CE.Global.CEUserType.Customer) && Convert.ToInt32(Session[CE.Global.General.UserTypeId]) !=
                Convert.ToInt32(CE.Global.CEUserType.Provider))
            {
                //Response.Redirect("sign-in");
                Response.Redirect(CE.Global.General.GetUrl("/car-insurance/trueyou-car-quote", Page));
            }
        }
        else
        {
            //Response.Redirect("sign-in");
            Response.Redirect(CE.Global.General.GetUrl("/car-insurance/trueyou-car-quote", Page));
        }

        if (Session[General.CarId] == null || Session[General.CarPolicyId] == null)
        {
            string isCXLive = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.IsCXLive").ToString();

            Response.Redirect("~/car-insurance/trueyou-car-quote");
        }
        else
        {
            //hplCarResults.NavigateUrl = "";
        }

        if (Session[General.IsCarRestoreResult] != null)
        {
            //hplProfile.NavigateUrl = "";
            //hplCarDetails.NavigateUrl = "";
        }

        if (Page.ClientScript.IsStartupScriptRegistered("addScriptShowHideAll") == false)
        {
            Page.ClientScript.RegisterStartupScript(Type.GetType("System.String"), "addScriptShowHideDriver", "ShowHideAll()", true);
        }
        if (Page.IsPostBack)
        {
            Session["IsFromAutoLogin"] = "0";
        }
        if (!Page.IsPostBack)
        {
            #region Promotion Display
            Int64 _carId = 0;
            if (Session[General.CarId] != null)
            {
                if (!Int64.TryParse(Session[General.CarId].ToString(), out _carId))
                {
                    _carId = 0;
                }
            }
            GetPromotionDetails(_carId);
            #endregion

            aCallme.HRef = CE.Global.General.GetUrl("/car-insurance/no-match-found", Page);

            txtEmailPop.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtEmailPop.ClientID + "','" + rfvEmailPop.ClientID + "','" + revEmailPop.ClientID + "');");
            txtNamePop.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtNamePop.ClientID + "','" + rfvNamePop.ClientID + "','" + revNamePop.ClientID + "');");
            txtMobilePop.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtMobilePop.ClientID + "','" + rfvMobilePop.ClientID + "','" + revMobilePop.ClientID + "');");
            ddlCallMeTime.Attributes.Add("onblur", "ShowValidationEffect('" + ddlCallMeTime.ClientID + "','" + rfvCallMeTime.ClientID + "');");

            if (Session[CE.Global.General.UserEmail] != null)
            {
                txtEmailPop.Text = Session[CE.Global.General.UserEmail].ToString();
            }
            if (Session[CE.Global.General.UserName] != null)
            {
                txtNamePop.Text = Session[CE.Global.General.UserName].ToString();
            }
            if (Session[CE.Global.General.UserPhoneNo] != null)
            {
                txtMobilePop.Text = Session[CE.Global.General.UserPhoneNo].ToString();
            }
            //Meng Pan Added on 01 Aug 2014 - Start
            Uri theRealURL = new Uri(HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.RawUrl);
            string rq_type = HttpUtility.ParseQueryString(theRealURL.Query).Get("type");
            if (rq_type != null && rq_type != string.Empty)
            {
            }
            //Meng Pan Added 01 Aug Jun 2014 - End

            Session["CIMSG"] = null;
            Session["UMMSG"] = null;

            Session[CE.Global.General.CarResultId] = null;
            if (1 != 1)// if (Session[General.UserId] != null && !CheckViewCount())
            {
                //ivMessage.Visible = true;
                //lblMessage.Visible = true;
                //lblMessage.Text = "<br />Due to speed optimization reasons, each user is restricted to 5 quotes per day.<br />Please visit us tomorrow.";
                //return;
            }
            else
            {
                int resultCalculatePremium = 0;
                //CAR POLICY DETAILS
                CarPolicy _carpolicy = new CarPolicy();
                CarPolicyDB _carpolicydb = new CarPolicyDB();
                Int64 _refceuserid = 0;
                Int64 _carid = 0;

                if (Session[General.UserId] != null)
                {
                    _refceuserid = Convert.ToInt64(Session[General.UserId].ToString());
                }

                if (Session[General.CarId] != null)
                {
                    _carid = Convert.ToInt64(Session[General.CarId].ToString());
                }

                _carpolicy = _carpolicydb.GetCarPolicy(_carid, _refceuserid);
                if (_carpolicy.NInfo5 == null || _carpolicy.NInfo5 == 0)
                {
                    if ((Session["IsFromAutoLogin"] == null) || (Session["IsFromAutoLogin"] != null && Session["IsFromAutoLogin"].ToString() != "1"))
                    {
                        resultCalculatePremium = CalculatePremiumCountResults();
                    }
                }
                else if (_carpolicy.NInfo5 != null && _carpolicy.NInfo5 == 1)
                {
                    if ((Session["IsFromAutoLogin"] == null) || (Session["IsFromAutoLogin"] != null && Session["IsFromAutoLogin"].ToString() != "1"))
                        resultCalculatePremium = CalculatePremium();
                    if (resultCalculatePremium > 0)
                        lblCompareInfo.Text = Resources.CarInsuranceResultPage.Compare4Items;
                    else
                        lblCompareInfo.Text = Resources.CarInsuranceResultPage.NoMatchQuote;

                }
                LoadDOB();
                LoadOccupation();
                ShowQuoteSummary();
                #region GetSearch
                LoadManufactYearList();
                ClearAllList();

                if (Session[General.CarPolicyId] != null && Session[General.CarId] != null)
                {
                    Int64 _cecarid = Convert.ToInt64(Session[General.CarId]);
                    Int64 _cepolicyid = Convert.ToInt64(Session[General.CarPolicyId]);
                    ShowCarAndPolicyDetail(_cecarid, _cepolicyid, 0);
                    DriverSetting();
                    OtherValidation();
                }
                else
                {
                    DriverSetting();
                }

                Int64 _userId = 0;
                if (Session[General.UserId] == null && Session[General.CarId] != null && Session[CE.Global.General.UserProfileAndContactComplete] != null)
                {
                    ShowCustomerDetailByCar(Convert.ToInt64(Session[General.CarId].ToString()));
                }
                else if (Session[General.UserId] != null)
                {
                    //checkIsAgreement.Visible = false;

                    _userId = Convert.ToInt64(Session[General.UserId].ToString());
                    if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                        Convert.ToInt32(CE.Global.CEUserType.Customer))
                    {
                        ShowCustomerDetail(_userId);
                    }
                    else if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                        Convert.ToInt32(CE.Global.CEUserType.Provider))
                    {
                        ShowCustomerDetail(_userId);
                    }
                }

                if (rdoYesClaimLastYear.Checked || rdoNoClaimLastYear.Checked) txtAnyClaim.Text = "1";
                if (rdoYesCTPL.Checked || rdoNoCTPL.Checked) txtCTPL.Text = "1";

                Page.Form.DefaultButton = btnNext.UniqueID;

                #endregion

                #region Sorting

                if (Session[General.UserId] != null)
                {
                    Cache.Remove("CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString());
                }
                else
                {
                    Cache.Remove("CarResult" + Session[General.CarId].ToString());
                }

                if (ViewState["SortOrder"] == null)
                {
                    ViewState["SortOrder"] = SortDirection.Ascending.ToString();
                }

                if (ViewState["SortExpression"] == null)
                {
                    ViewState["SortExpression"] = "";
                }

                if (Request.Params["sortby"] != null)
                {
                    int _sortBy = 0;
                    if (Int32.TryParse(Request.Params["sortby"].ToString(), out _sortBy))
                    {
                        string _sortExpress = "";
                        string _sortOrder = "";

                        if (_sortBy == 0)
                        {
                            _sortExpress = "AnnualPremium";
                            _sortOrder = " ASC";
                        }
                        else if (_sortBy == 1)
                        {
                            _sortExpress = "CompanyName";
                            _sortOrder = " ASC";
                        }
                        else if (_sortBy == 2)
                        {
                            _sortExpress = "PackageName";
                            _sortOrder = " ASC";
                        }
                        else if (_sortBy == 3)
                        {
                            _sortExpress = "TPPD";
                            _sortOrder = " DESC";
                        }
                        else if (_sortBy == 4)
                        {
                            _sortExpress = "TPBIP";
                            _sortOrder = " DESC";
                        }
                        else if (_sortBy == 5)
                        {
                            _sortExpress = "PADriver";
                            _sortOrder = " DESC";
                        }
                        else if (_sortBy == 6)
                        {
                            _sortExpress = "PAPassenger";
                            _sortOrder = " ASC";
                        }
                        else if (_sortBy == 7)
                        {
                            _sortExpress = "MedicalExpense";
                            _sortOrder = " ASC";
                        }
                        else
                        {
                            _sortExpress = "BailBond";
                            _sortOrder = " ASC";
                        }

                        ViewState["SortExpression"] = _sortExpress;
                        if (_sortOrder == " ASC")
                            ViewState["SortOrder"] = SortDirection.Ascending.ToString();
                        else
                            ViewState["SortOrder"] = SortDirection.Descending.ToString();
                    }
                    else
                    {
                        ViewState["SortExpression"] = "AnnualPremium";
                        ViewState["SortOrder"] = SortDirection.Ascending.ToString();
                    }
                }
                else
                {
                    ViewState["SortExpression"] = "Info2, PromotionPrice";
                    ViewState["SortOrder"] = SortDirection.Ascending.ToString();
                }

                #endregion

                //NEED TO EDIT
                #region One Id One Privilege
                Int32 _InsuranceCount = 0;
                if (hdnPromoId.Value == "4" && hdnPromoCode.Value != null)
                {
                    Int64 _UserId = 0;
                    if (Session[General.UserId] != null)
                    {
                        if (!Int64.TryParse(Session[General.UserId].ToString(), out _UserId))
                        {
                            _UserId = 0;
                        }
                    }
                    if (_UserId > 0)
                    {
                        _InsuranceCount = GetBuyInsuranceCount(_UserId);
                    }
                }
                if (_InsuranceCount > 0)
                {
                    divResultDisplayFilter.Style.Add("display", "none");
                    divResultDisplay.Style.Add("display", "none");
                    divCantBuy.Visible = true;
                    divSerchbar.Visible = false;
                    divNomatchCallBack.Visible = false;
                    divNomatch.Visible = false;
                    lblNomatch.Text = "";

                    divbtnQS.Style.Add("display", "none");
                    divbtnEQ.Style.Add("display", "none");
                    divbtnNQ.Style.Add("display", "none");
                }
                else
                {
                    divSerchbar.Visible = true;
                    divbtnQS.Style.Add("display", "");
                    divbtnEQ.Style.Add("display", "");
                    divbtnNQ.Style.Add("display", "none");
                    divResultDisplayFilter.Style.Add("display", "");
                    divResultDisplay.Style.Add("display", "");
                    divCantBuy.Visible = false;
                    ResultsQuotesDataBind();
                }
                //ResultsQuotesDataBind();
                #endregion
                DriverSetting();
                General.ClearAllSession(this.Page, "CI");
            }
        }
    }

    protected void ShowHideAllClassesSelection(bool status)
    {
        if (status)
        {
            ListItemCollection _licInsuranceType = new ListItemCollection();
            _licInsuranceType.Add(new ListItem(Resources.General.All, "0"));
            foreach (ListItem item in ddlInsuranceType.Items)
            {
                _licInsuranceType.Add(item);
            }
            ddlInsuranceType.Items.Clear();

            foreach (ListItem item in _licInsuranceType)
            {
                ddlInsuranceType.Items.Add(item);
            }
        }
        else
        {
            if (ddlInsuranceType.Items[0].Value == "0")
            {
                ddlInsuranceType.Items.RemoveAt(0);
            }
        }
    }

    private void ShowQuoteSummary()
    {
        CarDetailTH _cardetail = new CarDetailTH();
        CarPolicy _carpolicy = new CarPolicy();

        CarDetailTHDB _cardetaildb = new CarDetailTHDB();
        CarPolicyDB _carpolicydb = new CarPolicyDB();

        ProfileDB _profiledb = new ProfileDB();
        Profile _profile = new Profile();

        Int64 _refceuserid = 0;
        Int64 _carid = 0;

        if (Session[General.UserId] != null)
        {
            _refceuserid = Convert.ToInt64(Session[General.UserId].ToString());
        }

        if (Session[General.CarId] != null)
        {
            _carid = Convert.ToInt64(Session[General.CarId].ToString());
            _cardetail = _cardetaildb.GetCar(_carid, _refceuserid);
        }
        _carpolicy = _carpolicydb.GetCarPolicy(_carid, _refceuserid);

        if (_cardetail != null && _carpolicy != null)
        {
            if (hdnURLFrom.Value == "bci")
            {
                lblAdvertiser.Text = "<img src=\"https://cv.accesstrade.in.th/cv.php?identifier=" + _cardetail.RowGUID + "&mcn=1f0e3dad99908345f7439f8ffabdffc4&result_id=100\" width=\"1\" height=\"1\" />";
            }
            lblYrofManufacture.Text = _cardetail.ManufactYear.ToString();
            lblYrofManTop.Text = _cardetail.ManufactYear.ToString();
            lblCarYearEdit.Text = _cardetail.ManufactYear.ToString();

            lblCarMakemodel.Text = _cardetail.MakeModelDesc;
            lblCarMakemodelTop.Text = _cardetail.MakeModelDesc;
            lblCarModelEdit.Text = _cardetail.MakeModelDesc;
            lblCarMakeCode.Text = _cardetail.CarMakeName;
            lblCarMakeName.Text = _cardetail.CarMakeName;
            lblCarModelFamilyName.Text = _cardetail.CarModelName.Replace('_', ' ');
            if (lblCarMakemodelTop.Text.Length > 40)
            {
                //lblCarMakemodelTop.Font.Size = new FontUnit(8.0d);
                lblCarMakemodelTop.ToolTip = _cardetail.MakeModelDesc;
            }

            #region Show Quotes Summary
            lblModificationAmount.Text = "";
            trModificationAmount.Visible = false;
            lblAnyModification.Text = Resources.CarInsurance.Option_No;
            if (_carpolicy.IsAddAccMod)
            {
                lblAnyModification.Text = Resources.CarInsurance.Option_Yes;
                trModificationAmount.Visible = true;
                lblModificationAmount.Text = _carpolicy.AddAccModAmount.ToString("#0,000.00");
            }
            lblCommencementDate.Text = _carpolicy.CoverageCommenceDate.ToString("dd/MM/yyyy");

            lblGarageType.Text = Resources.CarInsurance.Garage_Authorized;
            if (_carpolicy.GarageType == 2)
            {
                lblGarageType.Text = Resources.CarInsurance.Garage_Dealer;
            }

            lblProvinceofRegistration.Text = Resources.CarInsurance.Province_UPC;
            if (_carpolicy.ProvinceRegistration == "BKK")
            {
                lblProvinceofRegistration.Text = Resources.CarInsurance.Province_BKK;
            }

            lblAnyClaimLastYear.Text = Resources.CarInsurance.Option_No;
            if (_carpolicy.IsClaimLastYear)
            {
                lblAnyClaimLastYear.Text = Resources.CarInsurance.Option_Yes;
            }

            lblDeductible.Text = Resources.CarInsurance.Option_DeductAll;
            if (_carpolicy.Deductible == 0)
            {
                lblDeductible.Text = Resources.CarInsurance.Option_No;
            }
            else if (_carpolicy.Deductible != -1 && _carpolicy.Deductible != 0)
            {
                lblDeductible.Text = Resources.CarInsurance.Option_Yes;
            }

            lblIncludeCTPL.Text = Resources.CarInsurance.Option_No;
            if (_carpolicy.IsCTPL)
            {
                lblIncludeCTPL.Text = Resources.CarInsurance.Option_Yes;
            }

            trGarageType.Visible = false;
            trProvinceofRegistration.Visible = false;
            trAnyClaimLastYear.Visible = false;
            trDeductible.Visible = false;
            trAnyModification.Visible = false;
            trIncludeCTPL.Visible = true;
            #endregion

            //divCTPL.Visible = false;
            divGarageType.Style.Add("display", "");
            divDeduct.Style.Add("display", "");
            //divAnyClaimLastYear.Style.Add("display", "");
            divDriver.Style.Add("display", "none");
            divYesAccMod.Style.Add("display", "none");
            divCTPL.Style.Add("display", "");
            switch (_carpolicy.InsuranceType)
            {
                case 0: //all classes
                    lblInsuranceType.Text = Resources.General.All;
                    ddlInsuranceType.SelectedIndex = ddlInsuranceType.Items.IndexOf(ddlInsuranceType.Items.FindByValue("0"));
                    trGarageType.Visible = true;
                    trDeductible.Visible = true;
                    trIncludeCTPL.Visible = true;
                    break;
                case 10: //class 1
                    lblInsuranceType.Text = "1";
                    ddlInsuranceType.SelectedIndex = ddlInsuranceType.Items.IndexOf(ddlInsuranceType.Items.FindByValue("10"));
                    //rdoNoCTPL.Checked = true;
                    trGarageType.Visible = true;
                    trDeductible.Visible = true;
                    trIncludeCTPL.Visible = true;
                    //trProvinceofRegistration.Visible = true;
                    //trAnyClaimLastYear.Visible = true;
                    //trAnyModification.Visible = true;
                    break;
                case 11: //class 1 (low cost)
                    lblInsuranceType.Text = "1+";
                    ddlInsuranceType.SelectedIndex = ddlInsuranceType.Items.IndexOf(ddlInsuranceType.Items.FindByValue("10"));
                    //rdoNoCTPL.Checked = true;
                    trGarageType.Visible = true;
                    trDeductible.Visible = true;
                    trIncludeCTPL.Visible = true;
                    //trProvinceofRegistration.Visible = true;
                    //trAnyClaimLastYear.Visible = true;
                    //trAnyModification.Visible = true;
                    break;
                case 21: //class 2+
                    lblInsuranceType.Text = "2+";
                    ddlInsuranceType.SelectedIndex = ddlInsuranceType.Items.IndexOf(ddlInsuranceType.Items.FindByValue("21"));
                    //rdoNoCTPL.Checked = true;

                    //divProvinceofRegistration.Visible = false;
                    //divAnyClaimLastYear.Visible = false;
                    //divDriver.Visible = false;
                    //divYesAccMod.Visible = false;
                    divGarageType.Style.Add("display", "");
                    divDeduct.Style.Add("display", "");
                    //divAnyClaimLastYear.Style.Add("display", "none");
                    divDriver.Style.Add("display", "none");
                    divYesAccMod.Style.Add("display", "none");
                    //divCTPL.Style.Add("display", "none");
                    divCTPL.Style.Add("display", "");

                    trGarageType.Visible = true;
                    trDeductible.Visible = true;
                    trIncludeCTPL.Visible = true;
                    //trProvinceofRegistration.Visible = false;
                    //trAnyClaimLastYear.Visible = false;
                    //trAnyModification.Visible = false;
                    //trModificationAmount.Visible = false;
                    break;
                case 31: //class 3+
                    lblInsuranceType.Text = "3+";
                    ddlInsuranceType.SelectedIndex = ddlInsuranceType.Items.IndexOf(ddlInsuranceType.Items.FindByValue("31"));
                    //rdoNoCTPL.Checked = true;

                    //divProvinceofRegistration.Visible = false;
                    //divAnyClaimLastYear.Visible = false;
                    //divDriver.Visible = false;
                    //divYesAccMod.Visible = false;
                    divGarageType.Style.Add("display", "");
                    divDeduct.Style.Add("display", "");
                    //divAnyClaimLastYear.Style.Add("display", "none");
                    divDriver.Style.Add("display", "none");
                    divYesAccMod.Style.Add("display", "none");
                    //divCTPL.Style.Add("display", "none");
                    divCTPL.Style.Add("display", "");

                    trGarageType.Visible = true;
                    trDeductible.Visible = true;
                    trIncludeCTPL.Visible = true;
                    //trProvinceofRegistration.Visible = false;
                    //trAnyClaimLastYear.Visible = false;
                    //trAnyModification.Visible = false;
                    //trModificationAmount.Visible = false;
                    break;
                case 30: //class 3
                    lblInsuranceType.Text = "3";
                    ddlInsuranceType.SelectedIndex = ddlInsuranceType.Items.IndexOf(ddlInsuranceType.Items.FindByValue("30"));

                    //divCTPL.Visible = true;
                    //divGarageType.Visible = false;
                    //divProvinceofRegistration.Visible = false;
                    //divAnyClaimLastYear.Visible = false;
                    //divDriver.Visible = false;
                    //divYesAccMod.Visible = false;
                    //divDeduct.Visible = false;
                    divCTPL.Style.Add("display", "");
                    divGarageType.Style.Add("display", "none");
                    //divAnyClaimLastYear.Style.Add("display", "none");
                    divDriver.Style.Add("display", "none");
                    divYesAccMod.Style.Add("display", "none");
                    divDeduct.Style.Add("display", "none");

                    trGarageType.Visible = false;
                    trDeductible.Visible = false;
                    trIncludeCTPL.Visible = true;
                    //trProvinceofRegistration.Visible = false;
                    //trAnyClaimLastYear.Visible = false;
                    //trAnyModification.Visible = false;
                    //trModificationAmount.Visible = false;
                    break;
            }



            //Foreigner Case - send Mail 
            if (_cardetaildb.GetForeignerCase(_cardetail.Info8, _cardetail.Info7) > 0)
            {
                //SendMailNotification(_cardetail);
            }

            txtAccModAmount.Attributes.Add("onblur", "ShowValidationEffectThree('" + txtAccModAmount.ClientID + "','" + rfvAccModAmount.ClientID + "','" + revAccModAmount.ClientID + "','" + csvAccModAmount.ClientID + "');");
            ddlInsuranceType.Attributes.Add("onblur", "ShowValidationEffect('" + ddlInsuranceType.ClientID + "','" + rfvInsuranceType.ClientID + "');");
            ddlGarageType.Attributes.Add("onblur", "ShowValidationEffect('" + ddlGarageType.ClientID + "','" + rfvGarageType.ClientID + "');");

            ddlNCB.Attributes.Add("onblur", "ShowValidationEffect('" + ddlNCB.ClientID + "','" + rfvNCB.ClientID + "');");
            ddlNCB.Attributes.Add("onfocus", "JT_ShowTwo('" + Resources.CarInsuranceToolTips.NCBDisclaimer + "', '" + ddlNCB.ClientID + "', '" + Resources.CarInsurance.NCB + "'); return true;");
            ddlNCB.Attributes.Add("onblur", "$('#JT').remove();ShowValidationEffect('" + ddlNCB.ClientID + "','" + rfvNCB.ClientID + "');");

            txtEmailAddress.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtEmailAddress.ClientID + "','" + rfvEmail.ClientID + "','" + rfvEmailValid.ClientID + "');");

        }

        _profile = null;
        _profiledb = null;
        _cardetail = null;
        _cardetaildb = null;
        _carpolicy = null;
        _carpolicydb = null;
    }

    private Int32 CalculatePremium()
    {
        int _result = 0;
        MyDatabase _db = new MyDatabase();
        SortedList _sPara = new SortedList();

        Int64 _carId = Convert.ToInt64(Session[General.CarId].ToString());
        Int64 _userId = 0;
        if (Session[General.UserId] != null)
        {
            _userId = Convert.ToInt64(Session[General.UserId].ToString());
        }
        _sPara.Add("@CarId", Session[General.CarId].ToString());
        _sPara.Add("@RefUserId", _userId);

        _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceClear]", _sPara);

        //select car detail
        _db = new MyDatabase();
        _sPara = new SortedList();
        DataTable _dt = new DataTable("tblModelBody");
        _sPara.Add("@CarId", Session[General.CarId].ToString());
        _sPara.Add("@RefCEUserId", _userId);
        _dt = _db.GetDataTableBySP("[sprocCarDetailTHSelectSingleItem]", _sPara);
        string[] makeName;
        makeName = _dt.Rows[0]["MakeModelDesc"].ToString().Split(' ');

        if (_dt.Rows.Count > 0)
        {

            _db = new MyDatabase();
            _sPara = new SortedList();
            _sPara.Add("@CarId", Session[General.CarId].ToString());
            _sPara.Add("@RefUserId", _userId);

            BKIDetailDB bki = new BKIDetailDB();

            if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                    Convert.ToInt32(CE.Global.CEUserType.Provider) && Session[CE.Global.General.ProviderCompanyId] != null)
            {
                if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.AZCPProviderCompanyID"))
                    _result = _db.ExecuteNonSqlSP("[sprocAZCPCarInsuranceCalculation]", _sPara);
                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.AXAProviderCompanyID"))
                    _result = _db.ExecuteNonSqlSP("[sprocAXACarInsuranceCalculation]", _sPara);
                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.MSIGProviderCompanyID"))
                    _result = _db.ExecuteNonSqlSP("[sprocMSIGCarInsuranceCalculation]", _sPara);
                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.LMGProviderCompanyID"))
                    _result = _db.ExecuteNonSqlSP("[sprocLMGCarInsuranceCalculation]", _sPara);
                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ChartisProviderCompanyID"))
                    _result = _db.ExecuteNonSqlSP("[sprocChartisCarInsuranceCalculation]", _sPara);
                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ThaivivatProviderCompanyID"))
                    _result = _db.ExecuteNonSqlSP("[sprocTVVCarInsuranceCalculation]", _sPara);
                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.BKIProviderCompanyID"))
                {
                    try
                    {
                        BKICalculationWithTimeout(_carId, _userId);
                    }
                    catch
                    {
                    }

                    _result = _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceCalculationBKI]", _sPara);
                }
            }
            else
            {
                //====Test Web Service
                try
                {
                    BKICalculationWithTimeout(_carId, _userId);
                }
                catch
                {
                }

                if (ddlInsuranceType.Text == "0")
                {
                    _result = (int)_db.ExecuteSP("[sprocProviderCarInsuranceCalculationWithAllInsuranceType]", _sPara);
                }
                else
                {
                    _result = _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceCalculation]", _sPara);
                }
            }
            return _result;
            //}
        }
        return 0;
    }

    private Int32 CalculatePremiumCountResults()
    {
        int _result = 0;
        MyDatabase _db = new MyDatabase();
        SortedList _sPara = new SortedList();

        Int64 _carId = Convert.ToInt64(Session[General.CarId].ToString());
        Int64 _userId = 0;
        if (Session[General.UserId] != null)
        {
            _userId = Convert.ToInt64(Session[General.UserId].ToString());
        }
        _sPara.Add("@CarId", Session[General.CarId].ToString());
        _sPara.Add("@RefUserId", _userId);

        _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceClear]", _sPara);

        //select car detail
        _db = new MyDatabase();
        _sPara = new SortedList();
        DataTable _dt = new DataTable("tblModelBody");
        _sPara.Add("@CarId", Session[General.CarId].ToString());
        _sPara.Add("@RefCEUserId", _userId);
        _dt = _db.GetDataTableBySP("[sprocCarDetailTHSelectSingleItem]", _sPara);
        string[] makeName;
        makeName = _dt.Rows[0]["MakeModelDesc"].ToString().Split(' ');

        if (_dt.Rows.Count > 0)
        {

            _db = new MyDatabase();
            _sPara = new SortedList();
            _sPara.Add("@CarId", Session[General.CarId].ToString());
            _sPara.Add("@RefUserId", _userId);

            BKIDetailDB bki = new BKIDetailDB();

            if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                    Convert.ToInt32(CE.Global.CEUserType.Provider) && Session[CE.Global.General.ProviderCompanyId] != null)
            {
                if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.AZCPProviderCompanyID"))
                    _result = _db.ExecuteNonSqlSP("[sprocAZCPCarInsuranceCalculation]", _sPara);
                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.AXAProviderCompanyID"))
                    _result = _db.ExecuteNonSqlSP("[sprocAXACarInsuranceCalculation]", _sPara);
                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.MSIGProviderCompanyID"))
                    _result = _db.ExecuteNonSqlSP("[sprocMSIGCarInsuranceCalculation]", _sPara);
                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.LMGProviderCompanyID"))
                    _result = _db.ExecuteNonSqlSP("[sprocLMGCarInsuranceCalculation]", _sPara);
                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ChartisProviderCompanyID"))
                    _result = _db.ExecuteNonSqlSP("[sprocChartisCarInsuranceCalculation]", _sPara);
                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ThaivivatProviderCompanyID"))
                    _result = _db.ExecuteNonSqlSP("[sprocTVVCarInsuranceCalculation]", _sPara);
                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.BKIProviderCompanyID"))
                {
                    try
                    {
                        BKICalculationWithTimeout(_carId, _userId);
                    }
                    catch
                    {
                    }

                    _result = _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceCalculationBKI]", _sPara);
                }
            }
            else
            {
                //====Test Web Service
                try
                {
                    BKICalculationWithTimeout(_carId, _userId);
                }
                catch
                {
                }

                _result = _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceCalculationWithResultCounting]", _sPara);

            }
            return _result;
            //}
        }
        return 0;
    }

    private void ResultsQuotesDataBind()
    {
        GetTempResultTableTwo();
        DataView dv = new DataView();
        if (Session[General.UserId] != null)
        {
            dv = new DataView((DataTable)Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()]);
        }
        else
        {
            dv = new DataView((DataTable)Cache["CarResult" + Session[General.CarId].ToString()]);
        }

        //LEE29/1/2015 
        if (dv.Count > 0)
        {
            if (ddlFilter.SelectedValue == "-1")
            {
                var rowData = from b in dv.ToTable("dtPackage").AsEnumerable()
                              group b by b["ProviderCompanyId"] into g
                              select g.OrderByDescending(m => m["PromotionPrice"]).First();


                DataTable _dtx = new DataTable();
                _dtx = rowData.CopyToDataTable();
                dv = _dtx.DefaultView;
            }
            else if (ddlFilter.SelectedValue != "-1")
            {
                if (ddlFilter.SelectedValue == "S")
                {
                    var rowData = from b in dv.ToTable("dtPackage").AsEnumerable()
                                  group b by b["ProviderCompanyId"] into g
                                  select g.OrderByDescending(m => m["SumInsured"]).First();


                    DataTable _dtx = new DataTable();
                    _dtx = rowData.CopyToDataTable();
                    dv = _dtx.DefaultView;
                }
                else if (ddlFilter.SelectedValue == "P")
                {
                    var rowData = from b in dv.ToTable("dtPackage").AsEnumerable()
                                  group b by b["ProviderCompanyId"] into g
                                  select g.OrderBy(m => m["PromotionPrice"]).First();


                    DataTable _dtx = new DataTable();
                    _dtx = rowData.CopyToDataTable();
                    dv = _dtx.DefaultView;
                }
            }
        }
        //endLEE


        string _strSort = "";
        if (ViewState["SortOrder"].ToString() == SortDirection.Ascending.ToString())
        {
            _strSort = " ASC";
        }
        else
        {
            _strSort = " DESC";
        }
        dv.Sort = ViewState["SortExpression"].ToString() + _strSort;

        //LEE 24/02/2015 if from partner page move their package to top
        string strTopPartner = "";
        if (Session["fromProvider"] != null && Session["fromProvider"].ToString() != "")
        {
            strTopPartner = Session["fromProvider"].ToString();
        }
        if (strTopPartner != "")
        {
            var rowList = dv.ToTable("dtPackage").AsEnumerable().ToList();
            var index = rowList.FindIndex(n => n["ProviderCompanyId"].ToString() == strTopPartner);
            if (index > 0)
            {
                var topItem = rowList[index];
                rowList.RemoveAt(index);
                rowList.Insert(0, topItem);
            }

            DataTable _dtx = new DataTable();
            _dtx = rowList.CopyToDataTable();
            dv = _dtx.DefaultView;
        }

        //LEE end

        foreach (DataRow dr in dv.Table.Rows)
        {
            if (dr["Info2"].ToString() == "10" || dr["Info2"].ToString() == "11")
                dr["Info2"] = Resources.CarInsurance.Insurance_ClassOne;
            else if (dr["Info2"].ToString() == "21")
                dr["Info2"] = Resources.CarInsurance.Insurance_ClassTwoPlus;
            else if (dr["Info2"].ToString() == "31")
                dr["Info2"] = Resources.CarInsurance.Insurance_ClassThreePlus;
            else if (dr["Info2"].ToString() == "30")
                dr["Info2"] = Resources.CarInsurance.Insurance_ClassThree;
        }

        rptCarResult.DataSource = dv;
        rptCarResult.DataBind();
        if (dv.Table.Rows.Count > 0)
        {
            divSerchbar.Visible = true;
            divNomatchCallBack.Visible = false;
            divNomatch.Visible = false;
            lblNomatch.Text = "";
            lblRecordCount.Text = Resources.CarInsuranceResultPage.WeFound + " " + dv.Table.Rows.Count + " " + Resources.CarInsuranceResultPage.Result4Carmodel; // " results for your car model";
        }
        else
        {
            divSerchbar.Visible = false;
            divNomatchCallBack.Visible = true;
            divNomatch.Visible = true;
            lblRecordCount.Text = "";
            lblNomatch.Text = Resources.General.SorryNomatchFound;// "Sorry. No results for your car model";
        }
    }

    private void SortGridViews(string strExpression)
    {
        if (Session[General.UserId] != null)
        {
            if (Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()] == null)
            {
                GetTempResultTableTwo();
            }
        }
        else
        {
            if (Cache["CarResult" + Session[General.CarId].ToString()] == null)
            {
                GetTempResultTableTwo();
            }
        }

        if (ViewState["SortOrder"] == null)
        {
            ViewState["SortOrder"] = SortDirection.Descending;
        }

        if (ViewState["SortExpression"] == null)
        {
            ViewState["SortExpression"] = SortDirection.Ascending.ToString();
        }

        DataView dv = new DataView();

        if (Session[General.UserId] != null)
        {
            dv = new DataView((DataTable)Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()]);
        }
        else
        {
            dv = new DataView((DataTable)Cache["CarResult" + Session[General.CarId].ToString()]);
        }
        string strSort = "";
        if (ViewState["SortOrder"].ToString() == SortDirection.Ascending.ToString())
        {
            if (ViewState["SortExpression"].ToString() == strExpression)
            {
                strSort = " DESC";
                ViewState["SortOrder"] = SortDirection.Descending.ToString();
                ViewState["SortExpression"] = strExpression;
            }
            else
            {
                strSort = " ASC";
                ViewState["SortOrder"] = SortDirection.Ascending.ToString();
                ViewState["SortExpression"] = strExpression;
            }

        }
        else
        {
            if (ViewState["SortExpression"].ToString() == strExpression)
            {
                strSort = " ASC";
                ViewState["SortOrder"] = SortDirection.Ascending.ToString();
                ViewState["SortExpression"] = strExpression;
            }
            else
            {
                strSort = " DESC";
                ViewState["SortOrder"] = SortDirection.Descending.ToString();
                ViewState["SortExpression"] = strExpression;
            }

        }

        dv.Sort = strExpression + strSort;

        rptCarResult.DataSource = dv;
        rptCarResult.DataBind();

    }

    private void GetTempResultTableTwo()
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dtResult = new DataTable();
        string _spName = "[sprocCarInsuranceResultSelectItemListTrueYouPromo]";
        SortedList _sPara = new SortedList();
        _sPara.Add("@CarId", Session[General.CarId].ToString());

        if (Session[General.UserId] != null)
        {
            _sPara.Add("@RefUserId", Session[General.UserId].ToString());
        }
        else
        {
            _sPara.Add("@RefUserId", 0);
        }
        _dtResult = _db.GetDataTableBySP(_spName, _sPara);
        if (_dtResult != null && _dtResult.Rows.Count > 0)
        {
        }
        else
        {
            Session["UMMSG"] = "CI,5000";
        }

        if (Session[General.UserId] != null)
        {
            Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()] = _dtResult;
        }
        else
        {
            Cache["CarResult" + Session[General.CarId].ToString()] = _dtResult;
        }
    }

    protected int GetRowNumber(string ctrlId)
    {
        int num = ctrlId.LastIndexOf("ctl");
        string index = ctrlId.Substring(num + 3, 2);
        int resultTemp = 0;
        int result = -1;
        if (int.TryParse(index, out resultTemp))
        {
            result = resultTemp;
        }
        return result;
    }

    public string GetFilePath()
    {
        string _filePath = CE.Configuration.MyConfigurationManager.GetAppSettingValue("FileOutputPath").ToString();
        _filePath += "exceloutput\\car_nomatch\\";
        CE.InputOut.MyIO _myIO = new CE.InputOut.MyIO();
        string _todaydate = General.GetUTCDateTime().ToString("yyyyMMMdd");
        if (!_myIO.CheckDirectory(_filePath + _todaydate))
        {
            if (_myIO.CreateDirectory(_filePath, _todaydate))
            {
                _filePath += _todaydate + "\\";
            }
        }
        else
        {
            _filePath += _todaydate + "\\";
        }

        return _filePath;
    }

    protected void rptCarResult_ItemCommand(object sender, RepeaterCommandEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            //HyperLink hplDetails = (HyperLink)e.Item.FindControl("hplDetails");
        }
        if (e.CommandName.ToLower().Equals("moreinfo"))
        {
            Label lblProviderId = (Label)e.Item.FindControl("lblProviderId");
            Session[CE.Global.General.ProviderCompanyId] = lblProviderId.Text;
            Label lblTempResultId = (Label)e.Item.FindControl("lblTempResultId");
            Session[CE.Global.General.CarResultId] = lblTempResultId.Text;

            //_redirectUrl = CE.Global.General.GetUrl("~/car-insurance/quote-details.aspx", Page);
            Response.Redirect(_redirectUrl);
        }
        else if (e.CommandName.ToLower().Equals("callfordiscount"))
        {
            if (CheckCallMeCount() < 3)
            {
                Label lblProviderId = (Label)e.Item.FindControl("lblProviderId");
                Session[CE.Global.General.ProviderCompanyId] = lblProviderId.Text;
                Label lblTempResultId = (Label)e.Item.FindControl("lblTempResultId");
                Session[CE.Global.General.CarResultId] = lblTempResultId.Text;
                Image imgPackageName = (Image)e.Item.FindControl("imgProvider");
                Label lblResultPremium = (Label)e.Item.FindControl("lblResultPremium");
                string strInsType = "";
                if (lblInsuranceType.Text == "1")
                {
                    strInsType = "10";
                }
                else if (lblInsuranceType.Text == "2+")
                {
                    strInsType = "21";
                }
                else if (lblInsuranceType.Text == "3")
                {
                    strInsType = "30";
                }
                else if (lblInsuranceType.Text == "3+")
                {
                    strInsType = "31";
                }
                if (Session[General.UserId] != null)
                {
                    //rdoExistingYes.Checked = true;
                }
                //divBrandPopup.Attributes.Add("class", GetMotorBrand(lblCarMakeCode.Text));
                divInsurerPopup.Attributes.Add("class", getProviderLogoCss(lblProviderId.Text, "moreinfo"));
                divMakeModelNamePopup.InnerHtml = lblCarMakeName.Text + " " + lblCarModelFamilyName.Text;
                divPremiumPopup.InnerHtml = "฿ " + lblResultPremium.Text;
                hidProvider.Value = lblProviderId.Text;
                ShowCallPopup();
                mpeCallPop.Show();
            }
            else
            {
                ScriptManager.RegisterStartupScript(Page, this.GetType(), "alert", "alert('" + Resources.General.Callback3Times + "');", true);
            }
        }
        else if (e.CommandName.ToLower().Equals("buyonline"))
        {
            Label lblProviderId = (Label)e.Item.FindControl("lblProviderId");
            Session[CE.Global.General.ProviderCompanyId] = lblProviderId.Text;
            Label lblTempResultId = (Label)e.Item.FindControl("lblTempResultId");
            Session[CE.Global.General.CarResultId] = lblTempResultId.Text;
            Label lblClassType = (Label)e.Item.FindControl("lblClassType");

            Response.Redirect(SetBuyNowUrl(lblProviderId.Text));
        }
        else if (e.CommandName.ToLower().Equals("compare"))
        {
            Label lblProviderId = (Label)e.Item.FindControl("lblProviderId");
            Session[CE.Global.General.ProviderCompanyId] = lblProviderId.Text;
            Label lblTempResultId = (Label)e.Item.FindControl("lblTempResultId");
            Session[CE.Global.General.CarResultId] = lblTempResultId.Text;
            Session["CITempResultId"] = hidStrResultCompare.Value;
            Response.Redirect(CE.Global.General.GetUrl("/car-insurance/compare-insurance", Page));
        }
    }

    protected void rptCarResult_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            //Button btnFindMore = (Button)e.Item.FindControl("btnFindMore");
            Button btnCompare = (Button)e.Item.FindControl("btnCompare");
            Label lblDeductible = (Label)e.Item.FindControl("lblDeductible");
            Label lblTempResultId = (Label)e.Item.FindControl("lblTempResultId");
            Label lblPackageName = (Label)e.Item.FindControl("lblPackageName");
            Label lblProviderId = (Label)e.Item.FindControl("lblProviderId");

            #region MoreInfo Controls
            Label lblPackageNameMoreInfo = (Label)e.Item.FindControl("lblPackageNameMoreInfo");
            Image imgProviderMoreInfo = (Image)e.Item.FindControl("imgProviderMoreInfo");
            HtmlGenericControl divProvider = (HtmlGenericControl)(e.Item.FindControl("divProvider"));
            HtmlGenericControl divProviderMoreInfo = (HtmlGenericControl)(e.Item.FindControl("divProviderMoreInfo"));
            HtmlGenericControl divFloodMoreInfo = (HtmlGenericControl)(e.Item.FindControl("divFloodMoreInfo"));
            Label lblOwnDamageTitleMoreInfo = (Label)e.Item.FindControl("lblOwnDamageTitleMoreInfo");
            Label lblTitleDeductibleMoreInfo = (Label)e.Item.FindControl("lblTitleDeductibleMoreInfo");
            Label lblDeductibleMoreInfo = (Label)e.Item.FindControl("lblDeductibleMoreInfo");
            Label lblTitleCoverOwnDamageMoreInfo = (Label)e.Item.FindControl("lblTitleCoverOwnDamageMoreInfo");
            Label lblCoverOwnDamageMoreInfo = (Label)e.Item.FindControl("lblCoverOwnDamageMoreInfo");
            Label lblTitleFireMoreInfo = (Label)e.Item.FindControl("lblTitleFireMoreInfo");
            Label lblFireMoreInfo = (Label)e.Item.FindControl("lblFireMoreInfo");
            Label lblTitleTheftMoreInfo = (Label)e.Item.FindControl("lblTitleTheftMoreInfo");
            Label lblTheftMoreInfo = (Label)e.Item.FindControl("lblTheftMoreInfo");
            Label lblAdditionalCoverMoreInfo = (Label)e.Item.FindControl("lblAdditionalCoverMoreInfo");
            Label lblCoverPADriverMoreInfo = (Label)e.Item.FindControl("lblCoverPADriverMoreInfo");
            Label lblPADriverMoreInfo = (Label)e.Item.FindControl("lblPADriverMoreInfo");
            Label lblCoverMEDMoreInfo = (Label)e.Item.FindControl("lblCoverMEDMoreInfo");
            Label lblMEDMoreInfo = (Label)e.Item.FindControl("lblMEDMoreInfo");
            Label lblCoverBailBondMoreInfo = (Label)e.Item.FindControl("lblCoverBailBondMoreInfo");
            Label lblBailBondMoreInfo = (Label)e.Item.FindControl("lblBailBondMoreInfo");
            Label lblThirdPartyMoreInfo = (Label)e.Item.FindControl("lblThirdPartyMoreInfo");
            Label lblTitleTPPDMoreInfo = (Label)e.Item.FindControl("lblTitleTPPDMoreInfo");
            Label lblTPPDMoreInfo = (Label)e.Item.FindControl("lblTPPDMoreInfo");
            Label lblTitleTPBIAMoreInfo = (Label)e.Item.FindControl("lblTitleTPBIAMoreInfo");
            Label lblTPBIAMoreInfo = (Label)e.Item.FindControl("lblTPBIAMoreInfo");
            Label lblTitleTPBIPMoreInfo = (Label)e.Item.FindControl("lblTitleTPBIPMoreInfo");
            Label lblTPBIPMoreInfo = (Label)e.Item.FindControl("lblTPBIPMoreInfo");
            Label lblPromo = (Label)e.Item.FindControl("lblPromo");
            Label lblDescription = (Label)e.Item.FindControl("lblDescription");
            imgProviderMoreInfo.Visible = false;
            #endregion

            bool IsEng = false;
            foreach (char ch in lblPackageName.Text.Trim().ToCharArray())
            {
                int x = (int)ch;
                if (x >= 63 && x <= 126)
                {
                    IsEng = true;
                    break;
                }
                else
                {
                    break;
                }
            }

            if (IsEng)
            {
                if (lblPackageName.Text.Trim().Length > 30)
                {
                    lblPackageName.Text = lblPackageName.Text.Trim().Substring(0, 30) + "...";
                    lblPackageNameMoreInfo.Text = lblPackageName.Text.Trim().Substring(0, 30) + "...";
                }
            }
            else
            {
                if (lblPackageName.Text.Trim().Length > 30)
                {
                    lblPackageName.Text = lblPackageName.Text.Trim().Substring(0, 30) + "...";
                    lblPackageNameMoreInfo.Text = lblPackageName.Text.Trim().Substring(0, 30) + "...";
                }
            }

            if (DataBinder.Eval(e.Item.DataItem, "DEC") != DBNull.Value && Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "DEC")) > 0)
            {
                lblDeductible.Text = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "DEC")).ToString("#,000");
                lblDeductibleMoreInfo.Text = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "DEC")).ToString("#,000");
            }
            else
            {
                lblDeductible.Text = Resources.CarInsuranceResultPage.Waived;
                lblDeductibleMoreInfo.Text = Resources.CarInsuranceResultPage.Waived;
            }

            Label lblSumInsured = (Label)e.Item.FindControl("lblSumInsured");
            if (Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "SumInsured")) > 0)
            {
                lblSumInsured.Text = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "SumInsured")).ToString("#,000");
                lblCoverOwnDamageMoreInfo.Text = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "SumInsured")).ToString("#,000");
            }
            else
            {
                lblSumInsured.Text = " - ";
                lblCoverOwnDamageMoreInfo.Text = " - ";
            }
            if (Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "Fire")) > 0)
            {
                lblFireMoreInfo.Text = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "Fire")).ToString("#,000");
            }
            else
            {
                lblFireMoreInfo.Text = " - ";
            }
            if (Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "Theft")) > 0)
            {
                lblTheftMoreInfo.Text = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "Theft")).ToString("#,000");
            }
            else
            {
                lblTheftMoreInfo.Text = " - ";
            }
            if (Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "IsFloodCover")) == 0)
            {

                HtmlGenericControl divflood = (HtmlGenericControl)(e.Item.FindControl("divFlood"));
                divflood.Visible = false;
                divFloodMoreInfo.Visible = false;

            }
            Label lblAnnualPremium = (Label)e.Item.FindControl("lblAnnualPremium");
            if (Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "AnnualPremium")) > 0)
            {
                lblAnnualPremium.Text = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "AnnualPremium")).ToString("#000.00");
            }

            Label lblDiscount = (Label)e.Item.FindControl("lblDiscount");
            Label lblPremiumPrice = (Label)e.Item.FindControl("lblPremiumPrice");
            if (Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "AnnualPremium")) == Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "PromotionPrice")))
            {
                HtmlGenericControl divDiscount = (HtmlGenericControl)(e.Item.FindControl("divDiscount"));
                divDiscount.Visible = false;
                lblPremiumPrice.Visible = false;

            }

            //Sakthi on 30 Jan 2015 for CNY - Start 
            if (Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "ClassType")) != 30 &&
                Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "AnnualPremium")) != Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "PromotionPrice")))
            {
                string _isPromo = hdnIsPromo.Value;
                if (_isPromo != null && _isPromo != string.Empty && _isPromo == "1")
                {
                    HtmlGenericControl divPromoIcon = (HtmlGenericControl)(e.Item.FindControl("divPromoIcon"));
                    divPromoIcon.Visible = true;
                }
            }
            //Sakthi on 30 Jan 2015 for CNY - End 

            //Sakthi on 27 Nov 2014 - Start
            bool IsIncludeCMI = false;
            float AnnualPremium = 0.0f;
            float PromotionPrice = 0.0f;
            if (!bool.TryParse(DataBinder.Eval(e.Item.DataItem, "IsIncludeCMI").ToString(), out IsIncludeCMI))
            {
                IsIncludeCMI = false;
            }
            Label lblCMI = (Label)e.Item.FindControl("lblCMI");
            Label lblBeforeCMI = (Label)e.Item.FindControl("lblBeforeCMI");
            Label lblAnnualPremiumDisplay = (Label)e.Item.FindControl("lblAnnualPremiumDisplay");
            Label lblPromotionPriceDisplay = (Label)e.Item.FindControl("lblPromotionPriceDisplay");
            HtmlGenericControl divCMITitle = (HtmlGenericControl)(e.Item.FindControl("divCMITitle"));
            HtmlGenericControl divTotalTitle = (HtmlGenericControl)(e.Item.FindControl("divTotalTitle"));
            HtmlGenericControl divBeforeCMI = (HtmlGenericControl)(e.Item.FindControl("divBeforeCMI"));
            HtmlGenericControl divCMI = (HtmlGenericControl)(e.Item.FindControl("divCMI"));
            HtmlGenericControl divPromoPremium = (HtmlGenericControl)(e.Item.FindControl("divPromoPremium"));
            if (IsIncludeCMI)
            {
                divCMITitle.Visible = true;
                divTotalTitle.Visible = true;
                divBeforeCMI.Visible = true;
                divCMI.Visible = true;
                divPromoPremium.Attributes.Add("class", "premium-cmi-promotion");
                float TotalCMI = 0.0f;
                float BeforeCMI = 0.0f;
                if (!float.TryParse(DataBinder.Eval(e.Item.DataItem, "TotalCMI").ToString(), out TotalCMI))
                {
                    TotalCMI = 0.0f;
                }
                if (!float.TryParse(DataBinder.Eval(e.Item.DataItem, "PromotionPrice").ToString(), out PromotionPrice))
                {
                    PromotionPrice = 0.0f;
                }
                if (!float.TryParse(DataBinder.Eval(e.Item.DataItem, "AnnualPremium").ToString(), out AnnualPremium))
                {
                    AnnualPremium = 0.0f;
                }
                BeforeCMI = PromotionPrice - TotalCMI;
                lblCMI.Text = TotalCMI.ToString("#000.00");
                lblBeforeCMI.Text = BeforeCMI.ToString("#,000.00");
                if (Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "AnnualPremium")) > 0)
                {
                    lblAnnualPremiumDisplay.Text = AnnualPremium.ToString("#,000.00");
                }
                if (Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "PromotionPrice")) > 0)
                {
                    lblPromotionPriceDisplay.Text = PromotionPrice.ToString("#,000.00");
                }
                if (AnnualPremium == PromotionPrice)
                {
                    lblAnnualPremiumDisplay.Text = "";
                }
            }
            else
            {
                divCMITitle.Visible = false;
                divTotalTitle.Visible = false;
                divBeforeCMI.Visible = false;
                divCMI.Visible = false;
                divPromoPremium.Attributes.Add("class", "premium-promotion");
                if (!float.TryParse(DataBinder.Eval(e.Item.DataItem, "PromotionPrice").ToString(), out PromotionPrice))
                {
                    PromotionPrice = 0.0f;
                }
                if (!float.TryParse(DataBinder.Eval(e.Item.DataItem, "AnnualPremium").ToString(), out AnnualPremium))
                {
                    AnnualPremium = 0.0f;
                }

                if (Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "AnnualPremium")) > 0)
                {
                    lblAnnualPremiumDisplay.Text = AnnualPremium.ToString("#,000.00");
                    //lblAnnualPremiumDisplay.Text = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "AnnualPremium")).ToString("#000.00");
                }
                if (Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "PromotionPrice")) > 0)
                {
                    lblPromotionPriceDisplay.Text = PromotionPrice.ToString("#,000.00");
                    //lblPromotionPriceDisplay.Text = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "PromotionPrice")).ToString("#000.00");
                }
                if (AnnualPremium == PromotionPrice)
                {
                    lblAnnualPremiumDisplay.Text = "";
                }
            }
            //Sakthi on 27 Nov 2014 - End

            Image imgProvider = (Image)e.Item.FindControl("imgProvider");
            HtmlGenericControl divSpecialNCB = (HtmlGenericControl)e.Item.FindControl("divSpecialNCB");
            if (imgProvider.AlternateText == "GluayGluay.com Special")
            {
                imgProvider.ImageUrl = "/images/gg-logo/gluaygluay-logo.png";
                imgProviderMoreInfo.ImageUrl = "/images/gg-logo/gluaygluay-logo.png";
                imgProviderMoreInfo.Visible = true;
                divProviderMoreInfo.Visible = false;
                imgProvider.Visible = true;
                divProvider.Visible = false;
                //HtmlImage imgS = (HtmlImage)e.Item.FindControl("imgSpecial");
                //imgS.Style.Add("display", "");
                //divSpecialNCB.Style.Add("display", "");
            }
            else
            {
                imgProviderMoreInfo.Visible = false;
                divProviderMoreInfo.Visible = true;
                imgProvider.Visible = false;
                divProvider.Visible = true;
            }
            if (Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "TPPD")) > 0)
            {
                lblTPPDMoreInfo.Text = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "TPPD")).ToString("#,000");
            }
            else
            {
                lblTPPDMoreInfo.Text = " - ";
            }
            if (Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "TPBIA")) > 0)
            {
                lblTPBIAMoreInfo.Text = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "TPBIA")).ToString("#,000");
            }
            else
            {
                lblTPBIAMoreInfo.Text = " - ";
            }
            if (Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "TPBIP")) > 0)
            {
                lblTPBIPMoreInfo.Text = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "TPBIP")).ToString("#,000");
            }
            else
            {
                lblTPBIPMoreInfo.Text = " - ";
            }
            if (Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "PADriver")) > 0)
            {
                lblPADriverMoreInfo.Text = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "PADriver")).ToString("#,000");
            }
            else
            {
                lblPADriverMoreInfo.Text = " - ";
            }
            if (Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "MedicalExpense")) > 0)
            {
                lblMEDMoreInfo.Text = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "MedicalExpense")).ToString("#,000");
            }
            else
            {
                lblMEDMoreInfo.Text = " - ";
            }
            if (Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "BailBond")) > 0)
            {
                lblBailBondMoreInfo.Text = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "BailBond")).ToString("#,000");
            }
            else
            {
                lblBailBondMoreInfo.Text = " - ";
            }
            divProvider.Attributes.Add("class", getProviderLogoCss(lblProviderId.Text, "result"));
            divProviderMoreInfo.Attributes.Add("class", getProviderLogoCss(lblProviderId.Text, "moreinfo"));
            SetProviderMoreInfo(lblProviderId.Text, lblPromo, lblDescription);
        }
    }

    public string SetBuyNowUrl(string providerid)
    {
        string _redirectUrl = string.Empty;
        _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/proposal-form.aspx", Page);
        //if (providerid == "11")
        //{
        //    _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/azcp-proposal-form.aspx", Page);
        //}
        //else if (providerid == "12")
        //{
        //    _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/msig-proposal-form", Page);
        //}
        //else if (providerid == "16")
        //{
        //    _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/axa-proposal-form", Page);
        //}
        //else if (providerid == "29")
        //{
        //    _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/lmg-proposal-form", Page);
        //}
        //else if (providerid == "31")
        //{
        //    _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/aig-proposal-form", Page);
        //}
        //else if (providerid == "32")
        //{
        //    _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/bki-proposal-form", Page);
        //}
        //else if (providerid == "33")
        //{
        //    _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/mti-proposal-form", Page);
        //}
        //else if (providerid == "35")
        //{
        //    _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/krungthai-proposal-form", Page);
        //}
        //else if (providerid == "39")
        //{
        //    _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/mittare-proposal-form", Page);
        //}
        //else if (providerid == "41")
        //{
        //    _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/ksk-proposal-form", Page);
        //}
        //else if (providerid == "43")
        //{
        //    _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/synmunkong-proposal-form", Page);
        //}
        //else if (providerid == "45")
        //{
        //    _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/viriyah-proposal-form", Page);
        //}
        //else if (providerid == "46")
        //{
        //    _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/tms-proposal-form", Page);
        //}
        //else if (providerid == "51")
        //{
        //    _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/scsmg-proposal-form", Page);
        //}
        //else if (providerid == "58")
        //{
        //    _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/tvv-proposal-form", Page);
        //}
        //else if (providerid == "65")
        //{
        //    _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/dhipaya-proposal-form", Page);
        //}
        //else if (providerid == "66")
        //{
        //    _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/thaipaiboon-proposal-form", Page);
        //}
        //else if (providerid == "67")
        //{
        //    _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/deves-proposal-form.aspx", Page);
        //}
        //else if (providerid == "68")
        //{
        //    _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/thaisri-proposal-form.aspx", Page);
        //}
        return _redirectUrl;
    }

    private void ShowCallPopup()
    {
        Int64 UserId = Convert.ToInt64(Session[General.UserId]);
        Profile _profile = new Profile();
        ProfileDB _profiledb = new ProfileDB();
        Contact _contact = new Contact();
        ContactDB _contactdb = new ContactDB();

        _profile = _profiledb.GetProfile(UserId);
        _profiledb = null;

        if (_profile != null)
        {
            //txtCallMeFullNamePop.Text = _profile.FirstName + " " + _profile.SurName;


            _contact = _contactdb.GetContact(UserId);
            if (_contact != null)
            {
                //usrCallMePhoneNo.PhoneNo = _contact.Mobile;
                //txtEmailPop.Text = _contact.Email;
                //txtEmailPop.ReadOnly = true;

            }

            _profile = null;
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            if (txtMobilePop.Text.Trim().Length == 10)
            {
                string _message = "";
                string _title = "";
                string CallMeFullNamePop = "";
                string strInsType = "";
                string ExistingEmail = Session[General.UserEmail].ToString();

                ChangeValidationEffectServerSide("callme");
                if (IsValid)
                {
                    //Sakthi - Added on 23 Oct 2014 - Start
                    Int64 _UserId = 0;
                    Int64 _CarId = 0;
                    Int64 _ExistingUserId = 0;
                    if (Session[CE.Global.General.CarId] != null)
                    {
                        if (!Int64.TryParse(Session[CE.Global.General.CarId].ToString(), out _CarId))
                        {
                            _CarId = 0;
                        }
                    }
                    if (Session[CE.Global.General.UserId] != null)
                    {
                        if (!Int64.TryParse(Session[General.UserId].ToString(), out _ExistingUserId))
                        {
                            _ExistingUserId = 0;
                        }
                    }

                    Account _useraccount = new Account();
                    AccountDB _useraccountdb = new AccountDB();
                    _useraccount = _useraccountdb.GetUserAccount(txtEmailPop.Text.Trim(), Convert.ToInt32(CE.Global.CEUserType.Customer));
                    //Hide on 13 Nov 2014 //_useraccount = _useraccountdb.GetUserAccount(txtEmailPop.Text.Trim(), txtMobilePop.Text.Trim().ToLower(), Convert.ToInt32(CE.Global.CEUserType.Customer));
                    if (_useraccount != null && _useraccount.CEID > 0)
                    {
                        Session[CE.Global.General.UserId] = _useraccount.CEID.ToString();
                        Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
                        Session[CE.Global.General.UserEmail] = _useraccount.Email;
                        _UserId = _useraccount.CEID;
                        UpdateProfile(_UserId, _CarId);
                    }
                    else
                    {
                        General.ClearAllSession(this.Page, "USER");
                        UpdateProfile(_UserId, _CarId);
                        if (Session[CE.Global.General.UserId] != null)
                        {
                            if (!Int64.TryParse(Session[CE.Global.General.UserId].ToString(), out _UserId))
                            {
                                _UserId = 0;
                            }
                        }
                        _UserId = Convert.ToInt64(Session[CE.Global.General.UserId].ToString());
                        UpdateUserIdCarDetails(_CarId, _UserId, _ExistingUserId, ExistingEmail, "SWITCH", txtEmailPop.Text.Trim().ToLower(), Session[General.UserName].ToString(), txtMobilePop.Text.Trim());
                        SendMailToUser(txtEmailPop.Text.Trim().ToLower(), Session[General.UserName].ToString(), txtMobilePop.Text.Trim());
                        _strUserStatus = "SWITCH";
                    }
                    //Sakthi - Added on 23 Oct 2014 - End

                    CallMeFullNamePop = Session[General.UserName].ToString();
                    _message = "Customer Name: " + Server.HtmlEncode(CallMeFullNamePop);
                    _title = "Call Me Now - Call Me request by " + Server.HtmlEncode(CallMeFullNamePop);
                    SetCookies(Server.HtmlEncode(txtNamePop.Text.Trim()), txtEmailPop.Text.Trim().ToLower(), txtMobilePop.Text.Trim());
                    Int64 _result = 0;
                    ContactUser _cu = new ContactUser();
                    ContactUserDB _cudb = new ContactUserDB();

                    strInsType = lblInsuranceType.Text;

                    if (ddlInsuranceType.Text != "0")
                    {
                        _cu.InsuranceType = "CI-" + strInsType;
                    }
                    else
                    {
                        _cu.InsuranceType = "";
                    }

                    _cu.ProductId = _CarId;
                    _cu.RefCEUserId = _UserId;

                    _cu.ProviderCompanyId = Convert.ToInt64(hidProvider.Value);
                    _cu.ContactNo = txtMobilePop.Text.Trim();
                    _cu.FullName = Server.HtmlEncode(CallMeFullNamePop);
                    _cu.CallTime = Convert.ToInt16(ddlCallMeTime.Text);

                    if (Request.Params["spc"] != null)
                    {
                        if (Request.Params["spc"].ToString() == "1")
                        {
                            _cu.Info1 = "GG Promotion";
                        }
                    }
                    if (hdnPromoId.Value == "4" && hdnPromoCode.Value != "0")
                    {
                        _cu.Info4 = Server.HtmlEncode(hdnPromoCode.Value.Trim());
                        _cu.NInfo5 = Convert.ToInt32(hdnPromoId.Value.Trim());
                    }

                    _result = _cudb.Insert(_cu);

                    if (_result > 0)
                    {
                        #region Hide on 23 Oct 2014
                        //Profile _profile = new Profile();
                        //ProfileDB _profiledb = new ProfileDB();
                        //_profile = _profiledb.GetProfile(_cu.RefCEUserId);
                        //if (_profile != null && _profile.ProfileId > 0)
                        //{
                        //    _profile.SurName = string.Empty;
                        //    _profile.FirstName = Server.HtmlEncode(CallMeFullNamePop);
                        //    _profiledb.Insert(_profile);
                        //}
                        //_profile = null;
                        //_profiledb = null;

                        //Contact _contact = new Contact();
                        //ContactDB _contactdb = new ContactDB();
                        //_contact = _contactdb.GetContact(_cu.RefCEUserId);
                        //if (_contact != null && _contact.ContactId > 0)
                        //{
                        //    _contact.Mobile = txtMobilePop.Text.Trim();
                        //    _contactdb.Insert(_contact);
                        //}
                        //_contact = null;
                        //_contactdb = null;

                        //CE.CarInsurance.CarDetailTH _cardetail = new CE.CarInsurance.CarDetailTH();
                        //CE.CarInsurance.CarDetailTHDB _cardetailDB = new CE.CarInsurance.CarDetailTHDB();
                        //_cardetail = _cardetailDB.GetCar(_cu.ProductId, _cu.RefCEUserId);
                        //if (_cardetail != null && _cardetail.CarId > 0)
                        //{
                        //    _cardetail.Info7 = string.Empty;
                        //    _cardetail.Info8 = Server.HtmlEncode(CallMeFullNamePop);
                        //    _cardetailDB.Insert(_cardetail);
                        //}
                        //_cardetail = null;
                        //_cardetailDB = null;
                        #endregion
                        ScriptManager.RegisterStartupScript(Page, this.GetType(), "alertThxU", "alert('" + Resources.CarInsurance.CallMeMessage + "')", true);

                        #region Hide Call me email sending - Sakthi on 11 Dec 2014
                        //_message += "<img src='http://www.gluaygluay.com/images/callme/callme-home.png' /><br/>";
                        //_message += "<br/><br/>Insurance Type : " + strInsType;
                        //_message += "<br/><br/>Full Name : " + Server.HtmlEncode(CallMeFullNamePop);
                        //_message += "<br/><br/>Email : " + txtEmailPop.Text;
                        //_message += "<br/><br/>Contact No : " + txtMobilePop.Text.Trim();
                        //_message += "<br/><br/>Call Time : " + ddlCallMeTime.SelectedItem.Text;
                        //string _emailList = ConfigurationManager.AppSettings["TH.CICallMeMessageReceiver"].ToString();
                        //MyMailManager.SendCRMMessage(_emailList, _title, _message);
                        #endregion
                        //divCallMe.Visible = true;
                        //lblCallMeMessage.Text = Resources.CarInsurance.CallMeMessage;

                        ddlCallMeTime.SelectedIndex = 0;
                        //txtEmailPop.ReadOnly = true;
                        //ddlCallMeTime.Enabled = false;
                        //txtMobilePop.ReadOnly = true;
                        //btnSubmit.Enabled = false;
                        btnCancel_Click(null, null);
                        mpeCallPop.Hide();
                        //if (_strUserStatus == "CHANGE" || _strUserStatus == "SWITCH")
                        //{
                        //    Response.Redirect(CE.Global.General.GetUrl("/car-insurance/results", Page));
                        //}
                    }
                }
            }
        }
        catch (Exception ex)
        {
        }

    }

    protected void btnNext_Click(object sender, EventArgs e)
    {
        OtherValidation();
        ChangeValidationEffectServerSide("cardetail");
        Page.Validate("cardetail");
        if (Page.IsValid)
        {
            if (Save())
            {
                Int64 _userId = 0;
                Int64 _carId = Convert.ToInt64(Session[General.CarId].ToString());
                if (Session[General.UserId] != null)
                {
                    _userId = Convert.ToInt64(Session[General.UserId].ToString());
                }

                //if (UpdateProfile(_userId, _carId) > 0)
                if (UpdateCustomerDetailByCarId(_userId, _carId) > 0)
                {
                    int resultCalculatePremium = CalculatePremium();
                    if (resultCalculatePremium > 0)
                        lblCompareInfo.Text = Resources.CarInsuranceResultPage.Compare4Items;
                    else
                        lblCompareInfo.Text = Resources.CarInsuranceResultPage.NoMatchQuote;
                    
                    ResultsQuotesDataBind();

                    switch (Convert.ToInt32(ddlInsuranceType.Text))
                    {
                        case 0:
                        case 10:
                            divGarageType.Style.Add("display", "");
                            //divYesAccMod.Style.Add("display", "");
                            //divAnyClaimLastYear.Style.Add("display", "");
                            divDriver.Style.Add("display", "none");
                            divDeduct.Style.Add("display", "");
                            divCTPL.Style.Add("display", "");
                            break;
                        case 21:
                        case 31:
                            divGarageType.Style.Add("display", "");
                            divDeduct.Style.Add("display", "");
                            //divAnyClaimLastYear.Style.Add("display", "none");
                            divDriver.Style.Add("display", "none");
                            divYesAccMod.Style.Add("display", "none");
                            divCTPL.Style.Add("display", "");
                            break;
                        case 30:
                            divCTPL.Style.Add("display", "");
                            divGarageType.Style.Add("display", "none");
                            //divAnyClaimLastYear.Style.Add("display", "none");
                            divDriver.Style.Add("display", "none");
                            divYesAccMod.Style.Add("display", "none");
                            divDeduct.Style.Add("display", "none");
                            break;
                    }
                    ScriptManager.RegisterStartupScript(this, GetType(), "result", "ShowHideDiv('divEditQuotes',false);", true);
                }
            }
            else
            {
                lblMessage.Text = "Saving did NOT succeed!";
            }
        }
        else
        {
            if (!Page.IsValid)
            {
                string msg = "";
                // Loop through all validation controls to see which
                // generated the errors.
                foreach (IValidator aValidator in this.Validators)
                {
                    if (!aValidator.IsValid)
                    {
                        msg += "<br />" + aValidator.ErrorMessage;
                    }
                }
                Label1.Text = msg;
            }
            lblMessage.Text = "Please fill all require fields completly and correctly.";
        }


    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        mpeCallPop.Hide();
    }

    protected void btnRunNewQuote_Click(object sender, EventArgs e)
    {
        General.ClearAllSession(this.Page, "NEWCI");
        Response.Redirect(CE.Global.General.GetUrl("/car-insurance/trueyou-car-quote", Page));
    }

    private void ChangeValidationEffectServerSide(string strValidationGroup)
    {
        txtEmailPop.Text = HttpUtility.HtmlEncode(txtEmailPop.Text);
        txtNamePop.Text = HttpUtility.HtmlEncode(txtNamePop.Text);
        txtMobilePop.Text = HttpUtility.HtmlEncode(txtMobilePop.Text);

        #region Customer
        //Email
        if (rfvEmailPop.Enabled && rfvEmailPop.ValidationGroup == strValidationGroup)
        {
            rfvEmailPop.Validate();
            if (rfvEmailPop.IsValid == false)
            {
                txtEmailPop.ControlStyle.CssClass = "cb-fields validationError";
            }
            else
            {
                txtEmailPop.ControlStyle.CssClass = "cb-fields";
            }
        }
        else
        {
            txtEmailPop.ControlStyle.CssClass = "cb-fields";
        }

        if (revEmailPop.Enabled && revEmailPop.ValidationGroup == strValidationGroup)
        {
            if (rfvEmailPop.IsValid)
            {
                revEmailPop.Validate();
                if (revEmailPop.IsValid == false)
                {
                    txtEmailPop.ControlStyle.CssClass = "cb-fields validationError";
                }
                else
                {
                    txtEmailPop.ControlStyle.CssClass = "cb-fields";
                }
            }
        }
        else
        {
            txtEmailPop.ControlStyle.CssClass = "cb-fields";
        }

        //MobileNo
        if (rfvMobilePop.Enabled && rfvMobilePop.ValidationGroup == strValidationGroup)
        {
            rfvMobilePop.Validate();
            if (rfvMobilePop.IsValid == false)
            {
                txtMobilePop.ControlStyle.CssClass = "cb-fields validationError";
            }
            else
            {
                txtMobilePop.ControlStyle.CssClass = "cb-fields";
            }
        }
        else
        {
            txtMobilePop.ControlStyle.CssClass = "cb-fields";
        }

        if (revMobilePop.Enabled && revMobilePop.ValidationGroup == strValidationGroup)
        {
            if (rfvMobilePop.IsValid)
            {
                revMobilePop.Validate();
                if (revMobilePop.IsValid == false)
                {
                    txtMobilePop.ControlStyle.CssClass = "cb-fields validationError";
                }
                else
                {
                    txtMobilePop.ControlStyle.CssClass = "cb-fields";
                }
            }
        }
        else
        {
            txtMobilePop.ControlStyle.CssClass = "cb-fields";
        }

        //Name
        if (rfvNamePop.Enabled && rfvNamePop.ValidationGroup == strValidationGroup)
        {
            rfvNamePop.Validate();
            if (rfvNamePop.IsValid == false)
            {
                txtNamePop.ControlStyle.CssClass = "cb-fields validationError";
            }
            else
            {
                txtNamePop.ControlStyle.CssClass = "cb-fields";
            }
        }
        else
        {
            txtNamePop.ControlStyle.CssClass = "cb-fields";
        }

        if (revMobilePop.Enabled && revMobilePop.ValidationGroup == strValidationGroup)
        {
            if (rfvNamePop.IsValid)
            {
                revNamePop.Validate();
                if (revMobilePop.IsValid == false)
                {
                    txtNamePop.ControlStyle.CssClass = "cb-fields validationError";
                }
                else
                {
                    txtNamePop.ControlStyle.CssClass = "cb-fields";
                }
            }
        }
        else
        {
            txtNamePop.ControlStyle.CssClass = "cb-fields";
        }

        //Call Time
        if (rfvCallMeTime.Enabled && rfvCallMeTime.ValidationGroup == strValidationGroup)
        {
            rfvCallMeTime.Validate();
            if (rfvCallMeTime.IsValid == false)
            {
                ddlCallMeTime.ControlStyle.CssClass = "cb-fields-dropdown validationError";
            }
            else
            {
                ddlCallMeTime.ControlStyle.CssClass = "cb-fields-dropdown";
            }
        }
        else
        {
            ddlCallMeTime.ControlStyle.CssClass = "cb-fields-dropdown";
        }

        #endregion

        #region Car Quote

        //Insurance Type
        if (rfvInsuranceType.Enabled && rfvInsuranceType.ValidationGroup == strValidationGroup)
        {
            rfvInsuranceType.Validate();
            if (rfvInsuranceType.IsValid == false)
            {
                ddlInsuranceType.ControlStyle.CssClass = "assumption-field validationError";
            }
            else
            {
                ddlInsuranceType.ControlStyle.CssClass = "assumption-field";
            }
        }
        else
        {
            ddlInsuranceType.ControlStyle.CssClass = "assumption-field";
        }

        //Garage Type
        if (rfvGarageType.Enabled && rfvGarageType.ValidationGroup == strValidationGroup)
        {
            rfvGarageType.Validate();
            if (rfvGarageType.IsValid == false)
            {
                ddlGarageType.ControlStyle.CssClass = "assumption-field validationError";
            }
            else
            {
                ddlGarageType.ControlStyle.CssClass = "assumption-field";
            }
        }
        else
        {
            ddlGarageType.ControlStyle.CssClass = "assumption-field";
        }

        //Vehicle Type
        if (rfvVehicleType.Enabled && rfvVehicleType.ValidationGroup == strValidationGroup)
        {
            rfvVehicleType.Validate();
            if (rfvVehicleType.IsValid == false)
            {
                ddlVehicleType.ControlStyle.CssClass = "validationError";
            }
            else
            {
                ddlVehicleType.ControlStyle.CssClass = "";
            }
        }
        else
        {
            ddlVehicleType.ControlStyle.CssClass = "";
        }

        //Year of Manufaturer
        if (rfvManufactYear.Enabled && rfvManufactYear.ValidationGroup == strValidationGroup)
        {
            rfvManufactYear.Validate();
            if (rfvManufactYear.IsValid == false)
            {
                ddlManufactYear.ControlStyle.CssClass = "validationError";
            }
            else
            {
                ddlManufactYear.ControlStyle.CssClass = "";
            }
        }
        else
        {
            ddlManufactYear.ControlStyle.CssClass = "";
        }

        if (rfvCarMake.Enabled && rfvCarMake.ValidationGroup == strValidationGroup)
        {
            rfvCarMake.Validate();
            if (rfvCarMake.IsValid == false)
            {
                ddlCarMake.ControlStyle.CssClass = "validationError";
            }
            else
            {
                ddlCarMake.ControlStyle.CssClass = "";
            }
        }
        else
        {
            ddlCarMake.ControlStyle.CssClass = "";
        }

        if (rfvModelBodyCCDoor.Enabled && rfvModelBodyCCDoor.ValidationGroup == strValidationGroup)
        {
            rfvModelBodyCCDoor.Validate();
            if (rfvModelBodyCCDoor.IsValid == false)
            {
                ddlModelBodyCCDoor.ControlStyle.CssClass = "validationError";
            }
            else
            {
                ddlModelBodyCCDoor.ControlStyle.CssClass = "";
            }
        }
        else
        {
            ddlModelBodyCCDoor.ControlStyle.CssClass = "";
        }

        if (rfvSumInsured.Enabled && rfvSumInsured.ValidationGroup == strValidationGroup)
        {
            rfvSumInsured.Validate();
            if (rfvSumInsured.IsValid == false)
            {
                txtSumInsured.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtSumInsured.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtSumInsured.ControlStyle.CssClass = "";
        }

        //NCB
        if (rfvNCB.Enabled && rfvNCB.ValidationGroup == strValidationGroup)
        {
            rfvNCB.Validate();
            if (rfvNCB.IsValid == false)
            {
                ddlNCB.ControlStyle.CssClass = "validationError";
            }
            else
            {
                ddlNCB.ControlStyle.CssClass = "";
            }
        }
        else
        {
            ddlNCB.ControlStyle.CssClass = "";
        }

        //Any Claims in the Last 3 Years?
        if (rfvAnyClaim.Enabled && rfvAnyClaim.ValidationGroup == strValidationGroup)
        {
            rfvAnyClaim.Validate();
            if (rfvAnyClaim.IsValid == false)
            {
                lblYesClaimLastYear.ControlStyle.CssClass = "validationError";
                lblNoClaimLastYear.ControlStyle.CssClass = "validationError";
            }
            else
            {
                lblYesClaimLastYear.ControlStyle.CssClass = "";
                lblNoClaimLastYear.ControlStyle.CssClass = "";
            }
        }
        else
        {
            lblYesClaimLastYear.ControlStyle.CssClass = "";
            lblNoClaimLastYear.ControlStyle.CssClass = "";
        }

        //CTPL
        if (rfvCTPL.Enabled && rfvCTPL.ValidationGroup == strValidationGroup)
        {
            rfvCTPL.Validate();
            if (rfvCTPL.IsValid == false)
            {
                lblYesCTPL.ControlStyle.CssClass = "validationError";
                lblNoCTPL.ControlStyle.CssClass = "validationError";
            }
            else
            {
                lblYesCTPL.ControlStyle.CssClass = "";
                lblNoCTPL.ControlStyle.CssClass = "";
            }
        }
        else
        {
            lblYesCTPL.ControlStyle.CssClass = "";
            lblNoCTPL.ControlStyle.CssClass = "";
        }

        //Add Additional Name Driver
        if (rfvAddDriver.Enabled && rfvAddDriver.ValidationGroup == strValidationGroup)
        {
            rfvAddDriver.Validate();
            if (rfvAddDriver.IsValid == false)
            {
                lblYesAddDriver.ControlStyle.CssClass = "validationError";
                lblNoAddDriver.ControlStyle.CssClass = "validationError";
            }
            else
            {
                lblYesAddDriver.ControlStyle.CssClass = "";
                lblNoAddDriver.ControlStyle.CssClass = "";
            }
        }
        else
        {
            lblYesAddDriver.ControlStyle.CssClass = "";
            lblNoAddDriver.ControlStyle.CssClass = "";
        }

        //Car Driver 1 Day
        if (rfvDriver1Day.Enabled && rfvDriver1Day.ValidationGroup == strValidationGroup)
        {
            rfvDriver1Day.Validate();
            if (rfvDriver1Day.IsValid == false)
            {
                ddlDriver1Day.ControlStyle.CssClass = "assumption-field-2 validationError";
            }
            else
            {
                ddlDriver1Day.ControlStyle.CssClass = "assumption-field-2";
            }
        }
        else
        {
            ddlDriver1Day.ControlStyle.CssClass = "assumption-field-2";
        }

        //Car Driver 1 Month
        if (rfvDriver1Month.Enabled && rfvDriver1Month.ValidationGroup == strValidationGroup)
        {
            rfvDriver1Month.Validate();
            if (rfvDriver1Month.IsValid == false)
            {
                ddlDriver1Month.ControlStyle.CssClass = "assumption-field-2 validationError";
            }
            else
            {
                ddlDriver1Month.ControlStyle.CssClass = "assumption-field-2";
            }
        }
        else
        {
            ddlDriver1Month.ControlStyle.CssClass = "assumption-field-2";
        }

        //Car Driver 1 Year
        if (rfvDriver1Year.Enabled && rfvDriver1Year.ValidationGroup == strValidationGroup)
        {
            rfvDriver1Year.Validate();
            if (rfvDriver1Year.IsValid == false)
            {
                ddlDriver1Year.ControlStyle.CssClass = "assumption-field-2 validationError";
            }
            else
            {
                ddlDriver1Year.ControlStyle.CssClass = "assumption-field-2";
            }
        }
        else
        {
            ddlDriver1Year.ControlStyle.CssClass = "assumption-field-2";
        }

        //Car Driver 2 Day
        if (rfvDriver2Day.Enabled && rfvDriver2Day.ValidationGroup == strValidationGroup)
        {
            rfvDriver2Day.Validate();
            if (rfvDriver2Day.IsValid == false)
            {
                ddlDriver2Day.ControlStyle.CssClass = "assumption-field-2 validationError";
            }
            else
            {
                ddlDriver2Day.ControlStyle.CssClass = "assumption-field-2";
            }
        }
        else
        {
            ddlDriver2Day.ControlStyle.CssClass = "assumption-field-2";
        }

        //Car Driver 2 Month
        if (rfvDriver2Month.Enabled && rfvDriver2Month.ValidationGroup == strValidationGroup)
        {
            rfvDriver2Month.Validate();
            if (rfvDriver2Month.IsValid == false)
            {
                ddlDriver2Month.ControlStyle.CssClass = "assumption-field-2 validationError";
            }
            else
            {
                ddlDriver2Month.ControlStyle.CssClass = "assumption-field-2";
            }
        }
        else
        {
            ddlDriver2Month.ControlStyle.CssClass = "assumption-field-2";
        }

        //Car Driver 2 Year
        if (rfvDriver2Year.Enabled && rfvDriver2Year.ValidationGroup == strValidationGroup)
        {
            rfvDriver2Year.Validate();
            if (rfvDriver2Year.IsValid == false)
            {
                ddlDriver2Year.ControlStyle.CssClass = "assumption-field-2 validationError";
            }
            else
            {
                ddlDriver2Year.ControlStyle.CssClass = "assumption-field-2";
            }
        }
        else
        {
            ddlDriver2Year.ControlStyle.CssClass = "assumption-field-2";
        }
        #endregion
    }

    protected void ddlInsuranceType_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            if (Convert.ToInt32(ddlInsuranceType.Text) == 10)
            {
                ddlNCB.SelectedIndex = ddlNCB.Items.IndexOf(ddlNCB.Items.FindByValue("20"));
            }
            else if (Convert.ToInt32(ddlInsuranceType.Text) == 30)
            {
                ddlDeduct.SelectedIndex = 0;
            }
            //DriverSetting();
            ControlVisibleOnOff();
            ////Sakthi on 11 Nov 2014 - Start
            //if (Convert.ToInt32(ddlInsuranceType.Text) == 0)
            //{
            //    btnNext.Enabled = false;
            //}
            //else
            //{
            //    btnNext.Enabled = true;
            //}
            ////Sakthi on 11 Nov 2014 - End
        }
        catch
        {

        }
    }

    protected void ddlManufactYear_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            string carMakeValue = ddlCarMake.Text;
            string carModelValue = ddlModelBodyCCDoor.Text;

            if (ddlManufactYear.Text == "-1")
            {
                ClearAllList();
            }
            else
            {
                GetCarMakeList(ddlManufactYear.Text, ddlCarMake);
                if (ddlCarMake.Items.Count > 0)
                {
                    if (carMakeValue != "-1")
                    {
                        ddlCarMake.Text = carMakeValue;
                        ddlCarMake_SelectedIndexChanged(sender, e);

                        if (carModelValue != "-1" && ddlModelBodyCCDoor.Items.Count > 0)
                        {
                            ddlModelBodyCCDoor.Text = carModelValue;
                            ddlModelBodyCCDoor_SelectedIndexChanged(sender, e);
                        }
                    }
                    else
                    {

                    }
                }
            }
        }
        catch
        {

        }
    }

    protected void ddlCarMake_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlCarMake.Text == "-1")
        {
            ddlModelBodyCCDoor.Items.Clear();
            ddlModelBodyCCDoor.Items.Add(new ListItem(Resources.General.SelectCarModel, "-1"));

            txtSumInsured.Text = "0";
            lblSumInsured.Text = "0";
            txtGroupNo.Text = "-1";
        }
        else
        {
            GetCarModelDescList(ddlCarMake.Text, ddlManufactYear.Text, ddlModelBodyCCDoor);
            if (ddlModelBodyCCDoor.Items.Count > 0)
            {
                ddlModelBodyCCDoor.SelectedIndex = 0;
                ddlModelBodyCCDoor_SelectedIndexChanged(sender, e);
            }
        }
    }

    protected void ddlModelBodyCCDoor_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlManufactYear.SelectedIndex >= 0 && ddlCarMake.SelectedIndex >= 0 & ddlModelBodyCCDoor.SelectedIndex >= 0)
        {
            string[] _tempDesc = ddlModelBodyCCDoor.Text.Split(' ');
            string _model = "";
            string _body = "";
            string _cc = "";
            string _door = "";
            if (_tempDesc.Length == 5)
            {
                _model = _tempDesc[0];
                _body = _tempDesc[1];
                _cc = _tempDesc[2].Substring(0, _tempDesc[2].Length - 2);
                _door = _tempDesc[3];
            }
            else if (_tempDesc.Length == 6)
            {
                _model = _tempDesc[0] + " " + _tempDesc[1];
                _body = _tempDesc[2];
                _cc = _tempDesc[3].Substring(0, _tempDesc[3].Length - 2);
                _door = _tempDesc[4];
            }
            else if (_tempDesc.Length == 7)
            {
                _model = _tempDesc[0] + " " + _tempDesc[1] + " " + _tempDesc[2];
                _body = _tempDesc[3];
                _cc = _tempDesc[4].Substring(0, _tempDesc[4].Length - 2);
                _door = _tempDesc[5];
            }
            lblModelDesc.Text = "model : " + _model + ", body: " + _body + ", cc: " + _cc + ", door: " + _door;
            GetCarModelSumInsuredAmountAndVehicleType(ddlCarMake.Text, _model, _body, _cc, _door, ddlManufactYear.Text, txtSumInsured, lblSumInsured, lblCarVehicleType);
            txtNewSumInsured.Text = txtSumInsured.Text;
            if (rdoYesAccMod.Checked)
            {
                if (txtAccModAmount.Text.Length > 0)
                {
                    int _sumInsured = Convert.ToInt32(txtSumInsured.Text);
                    int _tmpAmount = 0;
                    if (Int32.TryParse(txtAccModAmount.Text, out _tmpAmount))
                    {
                        _sumInsured += _tmpAmount;
                        txtNewSumInsured.Text = _sumInsured.ToString();
                        lblSumInsured.Text = Convert.ToInt32(txtNewSumInsured.Text).ToString("#,000");
                    }
                    else
                    {
                        txtNewSumInsured.Text = _sumInsured.ToString();
                        txtAccModAmount.Text = "";
                    }
                }
            }
            GetCarModelGroupNo(ddlCarMake.Text, _model, _body, _cc, _door, txtGroupNo);
        }
    }

    protected void ddlDriverCount_SelectedIndexChanged(object sender, EventArgs e)
    {
        DriverSetting();
    }

    protected void ddlVehicleType_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlVehicleType.Text == "110")
        {
            if (lblCarVehicleType.Text == "PU")
            {
                //if (ddlVehicleType.Text == "110")
                //{
                //    _car.Info3 = "320";
                //}
                //else if (ddlVehicleType.Text == "120")
                //{
                //    _car.Info3 = "340"; //Disabled, No Packages
                //}

                //divSpecifyDriver.Visible = false;
            }
            else
            {
                divSpecifyDriver.Visible = true;
            }
        }
        else
        {
            divSpecifyDriver.Visible = false;
            rdoNoAddDriver.Checked = true;
            rdoNoAddDriver_CheckedChanged(sender, e);
        }

    }
    
    protected void ddlFilter_SelectedIndexChanged(object sender, EventArgs e)
    {
        btnNext_Click(sender, e);
    }

    private Int64 LogUserViewedHistory()
    {
        UserViewHistoryDB _userviewdb = new UserViewHistoryDB();
        return _userviewdb.LogViewedHistory("CI", Request, "Car Insurance car detail.");
    }

    private void ClearAllList()
    {
        ddlCarMake.Items.Clear();
        ddlCarMake.Items.Add(new ListItem(Resources.General.SelectCarMake, "-1"));
        ddlModelBodyCCDoor.Items.Clear();
        ddlModelBodyCCDoor.Items.Add(new ListItem(Resources.General.SelectCarModel, "-1"));
        txtSumInsured.Text = "0";
        lblSumInsured.Text = "0";
        txtGroupNo.Text = "-1";
    }

    private void ClickOnceButton(Page page, Button b)
    {
        System.Text.StringBuilder oneClickScript = new System.Text.StringBuilder();
        oneClickScript.Append("if (typeof(Page_ClientValidate) == 'function') { ");
        oneClickScript.Append("if (Page_ClientValidate() == false) { return false; }} ");
        oneClickScript.Append("this.value = 'Processing...';");
        oneClickScript.Append("this.disabled = true;");
        oneClickScript.Append(page.ClientScript.GetPostBackEventReference(b, ""));
        oneClickScript.Append(";");
        b.Attributes.Add("onclick", oneClickScript.ToString());
    }

    private bool Save()
    {
        try
        {
            Int64 _carresult = 0;
            Int64 _policyresult = 0;

            CarDetailTH _car = new CarDetailTH();
            CarDetailTHDB _cardb = new CarDetailTHDB();

            ProfileDB _profiledb = new ProfileDB();
            Profile _profile = new Profile();

            Contact _contact = new Contact();
            ContactDB _contactdb = new ContactDB();

            Int64 _refceuserid = 0;

            int _day1 = 1;
            int _month1 = 1;
            int _year1 = 1900;

            int _day2 = 1;
            int _month2 = 1;
            int _year2 = 1900;
            DateTime _dtDriverDOB1 = new DateTime(_year1, _month1, _day1);
            DateTime _dtDriverDOB2 = new DateTime(_year2, _month2, _day2);

            if (Convert.ToInt16(ddlDriverCount.Text) > 0 && rdoYesAddDriver.Checked)
            {
                _day1 = Convert.ToInt32(ddlDriver1Day.Text);
                _month1 = Convert.ToInt32(ddlDriver1Month.Text);
                _year1 = Convert.ToInt32(ddlDriver1Year.Text);
                if (!ValidDate(_year1, _month1, _day1))
                {
                    lblMessage.ForeColor = System.Drawing.Color.Red;
                    lblMessage.Text = "Please select valid DOB";
                    return true;
                }
                _dtDriverDOB1 = new DateTime(_year1, _month1, _day1);
                if (Convert.ToInt16(ddlDriverCount.Text) > 1)
                {
                    _day2 = Convert.ToInt32(ddlDriver2Day.Text);
                    _month2 = Convert.ToInt32(ddlDriver2Month.Text);
                    _year2 = Convert.ToInt32(ddlDriver2Year.Text);
                    if (!ValidDate(_year2, _month2, _day2))
                    {
                        lblMessage.ForeColor = System.Drawing.Color.Red;
                        lblMessage.Text = "Please select valid DOB";
                        return true;
                    } _dtDriverDOB2 = new DateTime(_year2, _month2, _day2);
                }
            }

            if (Session[General.CarId] != null)
            {
                _car = _cardb.GetCar(Convert.ToInt64(Session[General.CarId].ToString()), 0);
                if (Session[General.AgentId] != null)
                {
                    _car.Info5 = "UPDATE";
                }
            }
            else
            {
                if (Session[General.AgentId] != null)
                {
                    _car.Info4 = "NEW";
                }
            }

            if (Session[General.ViewedDetailsId] == null)
            {
                Session[General.ViewedDetailsId] = LogUserViewedHistory().ToString();
            }

            if (_car == null)
            {
                _car = new CarDetailTH();
            }

            if (Session[CE.Global.General.UserId] != null)
            {
                _refceuserid = Convert.ToInt64(Session[CE.Global.General.UserId]);
                _profile = _profiledb.GetProfile(_refceuserid);
                _contact = _contactdb.GetContact(_refceuserid);
                if (_profile != null && _contact != null)
                {
                    _car.Info5 = _contact.Email;
                    _car.Info6 = _contact.Mobile;
                    _car.Info7 = _profile.SurName;
                    if (_profile.FirstName.Trim().Length > 0)
                    {
                        _car.Info8 = _profile.FirstName;
                    }
                    _car.Info9 = (_profile.Gender.ToString().Trim() != "" ? _profile.Gender.ToString() : "M"); //ddlGender.GetGender();
                    if (_profile.DOB.Year == 1900)
                    {
                        DateTime dteDOB = new DateTime(1995, 1, 1);
                        _car.Info10 = dteDOB.ToString("dd-MMM-yyyy");
                    }
                    else
                    {
                        _car.Info10 = _profile.DOB.ToString("dd-MMM-yyyy");
                    }
                    _car.Info11 = _profile.Occupation.ToString();
                    _car.Info12 = _profile.JobNature;
                    _car.Info13 = _profile.MaritalStatus.ToString();
                    _car.Info14 = "0";
                    _car.Info15 = _profile.Salutation;
                    _profile = null;
                    _contact = null;
                }
            }

            _car.ManufactYear = Convert.ToInt32(ddlManufactYear.Text);
            if (Session[General.AgentId] != null)
            {
                _car.Info2 = Session[General.AgentId].ToString();
                _car.Info3 = General.GetUTCDateTime().ToString();
            }

            _car.CarMakeName = ddlCarMake.Text;
            string[] _tempDesc = ddlModelBodyCCDoor.SelectedValue.Split(' ');
            if (_tempDesc.Length == 5)
            {
                _car.CarModelName = _tempDesc[0];
                _car.Body = _tempDesc[1];
                _car.CC = Convert.ToInt32(_tempDesc[2].Substring(0, _tempDesc[2].Length - 2));
                _car.Door = Convert.ToInt32(_tempDesc[3]);
            }
            else if (_tempDesc.Length == 6)
            {
                _car.CarModelName = _tempDesc[0] + " " + _tempDesc[1];
                _car.Body = _tempDesc[2];
                _car.CC = Convert.ToInt32(_tempDesc[3].Substring(0, _tempDesc[3].Length - 2));
                _car.Door = Convert.ToInt32(_tempDesc[4]);
            }
            else if (_tempDesc.Length == 7)
            {
                _car.CarModelName = _tempDesc[0] + " " + _tempDesc[1] + " " + _tempDesc[2];
                _car.Body = _tempDesc[3];
                _car.CC = Convert.ToInt32(_tempDesc[4].Substring(0, _tempDesc[4].Length - 2));
                _car.Door = Convert.ToInt32(_tempDesc[5]);
            }
            _car.GroupNo = Convert.ToInt32(txtGroupNo.Text);
            _car.Info2 = lblCarVehicleType.Text;
            //LC = 210 or 220
            //PS = 110 or 120
            //PU = 320
            //SV = 110 or 120
            if (lblCarVehicleType.Text == "PS" || lblCarVehicleType.Text == "SV" || lblCarVehicleType.Text == "")
            {
                _car.Info3 = ddlVehicleType.Text;
            }
            else if (lblCarVehicleType.Text == "LC")
            {
                if (ddlVehicleType.Text == "110")
                {
                    _car.Info3 = "210";
                }
                else if (ddlVehicleType.Text == "120")
                {
                    _car.Info3 = "220";
                }
            }
            else if (lblCarVehicleType.Text == "PU")
            {
                if (ddlVehicleType.Text == "110" && _car.Door == 2)
                {
                    _car.Info3 = "320";
                }
                if (ddlVehicleType.Text == "110" && _car.Door == 4)
                {
                    _car.Info3 = "110";
                }
                else if (ddlVehicleType.Text == "120")
                {
                    _car.Info3 = "340"; //Disabled, No Packages
                }
            }
            _car.MakeModelDesc = ddlCarMake.SelectedItem.Text + " " + ddlModelBodyCCDoor.SelectedItem.Text;
            _car.Status = true;
            _car.RefCEUserId = _refceuserid;
            _car.ViewedDetailId = Convert.ToInt64(Session[General.ViewedDetailsId].ToString());
            _car.CurrentStep = 1;
            _car.TotalStep = 4;

            if (hidCurInsuranceCompany.Value.Trim() == "") hidCurInsuranceCompany.Value = "150";
            _car.Info1 = hidCurInsuranceCompany.Value;

            _carresult = _cardb.Insert(_car);

            //**********************************************************

            _car = null;
            _cardb = null;

            if (_carresult > 0)
            {
                Session[CE.Global.General.CarId] = _carresult.ToString();
            }
            else
            {
                lblMessage.Text = "Insert error!";
            }
            //return _result > 0;
            if (_carresult > 0)
            {
                //CAR POLICY DETAILS
                CarPolicy _carpolicy = new CarPolicy();
                CarPolicyDB _carpolicydb = new CarPolicyDB();
                Int64 _carId = Convert.ToInt64(Session[General.CarId].ToString());
                Int64 _carpolicyid = 0;

                if (Session[General.CarPolicyId] != null)
                {
                    _carpolicyid = Convert.ToInt64(Session[General.CarPolicyId].ToString());
                    _carpolicy.CECarPolicyId = _carpolicyid;
                    _carpolicy.NInfo5 = 1;
                    if (Session[General.AgentId] != null)
                    {
                        _carpolicy.Info5 = "UPDATE";
                    }
                }
                else
                {
                    if (Session[General.AgentId] != null)
                    {
                        _carpolicy.Info4 = "NEW";
                    }
                }

                lblMessage.Text = "";
                if (Session[General.AgentId] != null)
                {
                    _carpolicy.Info2 = Session[General.AgentId].ToString();
                    _carpolicy.Info3 = General.GetUTCDateTime().ToString();
                }

                _carpolicy.CECarId = _carId;
                _carpolicy.InsuranceType = Convert.ToInt32(ddlInsuranceType.Text);
                _carpolicy.GarageType = Convert.ToInt32(ddlGarageType.Text);
                _carpolicy.VehicleType = Convert.ToInt32(ddlVehicleType.Text);
                _carpolicy.SumInsured = Convert.ToInt32(txtSumInsured.Text);
                _carpolicy.ProvinceRegistration = "BKK";
                _carpolicy.UseOfVehicle = "N/A";
                string strDate = hidCoverageCommenceDate.Value;
                int _iDay = Convert.ToInt32(strDate.Substring(0, 2));
                int _iMonth = Convert.ToInt32(strDate.Substring(2, 2));
                int _iYear = Convert.ToInt32(strDate.Substring(4, 4));
                if (_iYear > 1)
                {
                    _carpolicy.CoverageCommenceDate = new DateTime(_iYear, _iMonth, _iDay);
                }
                else
                {
                    _carpolicy.CoverageCommenceDate = General.GetUTCDateTimeToday().AddDays(14);
                }
                _carpolicy.IsRedPlate = false;

                if (ddlInsuranceType.SelectedValue == "10" || ddlInsuranceType.SelectedValue == "11")
                {
                    _carpolicy.IsAddAccMod = rdoYesAccMod.Checked;
                    if (rdoYesAccMod.Checked)
                    {
                        int _tmpAccModAmount = 0;
                        if (Int32.TryParse(txtAccModAmount.Text, out _tmpAccModAmount))
                        {
                            _carpolicy.AddAccModAmount = _tmpAccModAmount;
                        }
                    }
                    else
                    {
                        _carpolicy.AddAccModAmount = 0;
                    }

                    if (Convert.ToInt32(ddlInsuranceType.Text) == 10)
                    {
                        ddlNCB.Text = "20";
                    }

                    if (Convert.ToInt32(ddlNCB.Text) >= 0)
                    {
                        _carpolicy.NCDPercent = Convert.ToInt32(ddlNCB.Text);
                    }
                    else
                    {
                        _carpolicy.NCDPercent = 0;
                    }
                    _carpolicy.IsClaimLastYear = rdoYesClaimLastYear.Checked;
                    _carpolicy.IsCTPL = rdoYesCTPL.Checked;
                    _carpolicy.IsAddDriver = rdoYesAddDriver.Checked;
                    if (rdoYesAddDriver.Checked)
                    {
                        _carpolicy.NoOfDriver = Convert.ToInt16(ddlDriverCount.SelectedValue);
                    }
                    else
                    {
                        _carpolicy.NoOfDriver = 0;
                    }
                }
                else
                {
                    _carpolicy.IsAddAccMod = false;
                    _carpolicy.AddAccModAmount = 0;
                    _carpolicy.NCDPercent = 0;
                    _carpolicy.IsClaimLastYear = false;
                    // On 07 Nov 2014 - sakthi - Start
                    //if (ddlInsuranceType.SelectedValue == "30")
                    //{
                    //    _carpolicy.IsCTPL = rdoYesCTPL.Checked;
                    //}
                    _carpolicy.IsCTPL = rdoYesCTPL.Checked;
                    // On 07 Nov 2014 - sakthi - End
                    _carpolicy.IsAddDriver = false;
                    _carpolicy.NoOfDriver = 0;
                }

                if (ddlInsuranceType.SelectedValue == "21" || ddlInsuranceType.SelectedValue == "31")
                {
                    if (Convert.ToInt16(ddlDeduct.SelectedValue) == 5000)
                    {
                        _carpolicy.Deductible = 2000;
                    }
                    else
                    {
                        _carpolicy.Deductible = Convert.ToInt16(ddlDeduct.SelectedValue);
                    }
                }
                else if (ddlInsuranceType.SelectedValue == "30")
                {
                    _carpolicy.Deductible = 0;
                }
                else
                {
                    _carpolicy.Deductible = Convert.ToInt16(ddlDeduct.SelectedValue);
                }

                if (hidCurrentInsurer.Value.Trim() == "") hidCurrentInsurer.Value = Resources.CarInsurance.Others;
                _carpolicy.CurrentInsurer = hidCurrentInsurer.Value;
                _carpolicy.RefCEUserId = _refceuserid;
                _carpolicy.Status = true;
                _carpolicy.CurrentStep = 2;
                _policyresult = _carpolicydb.Insert(_carpolicy);
                if (_policyresult > 0)
                {
                    Session[General.CarPolicyId] = _policyresult.ToString();

                    lblMessage.Text += "<br />Car policy saved successfully!";
                    lblMessage.ForeColor = System.Drawing.Color.Blue;


                    #region Show Quotes Summary
                    lblModificationAmount.Text = "";
                    trModificationAmount.Visible = false;
                    lblAnyModification.Text = Resources.CarInsurance.Option_No;
                    if (_carpolicy.IsAddAccMod)
                    {
                        lblAnyModification.Text = Resources.CarInsurance.Option_Yes;
                        trModificationAmount.Visible = true;
                        lblModificationAmount.Text = _carpolicy.AddAccModAmount.ToString("#0,000.00");
                    }
                    lblCommencementDate.Text = _carpolicy.CoverageCommenceDate.ToString("dd/MM/yyyy");

                    lblGarageType.Text = Resources.CarInsurance.Garage_Authorized;
                    if (_carpolicy.GarageType == 2)
                    {
                        lblGarageType.Text = Resources.CarInsurance.Garage_Dealer;
                    }

                    lblProvinceofRegistration.Text = Resources.CarInsurance.Province_UPC;
                    if (_carpolicy.ProvinceRegistration == "BKK")
                    {
                        lblProvinceofRegistration.Text = Resources.CarInsurance.Province_BKK;
                    }

                    lblAnyClaimLastYear.Text = Resources.CarInsurance.Option_No;
                    if (_carpolicy.IsClaimLastYear)
                    {
                        lblAnyClaimLastYear.Text = Resources.CarInsurance.Option_Yes;
                    }

                    lblDeductible.Text = Resources.CarInsurance.Option_DeductAll;
                    if (_carpolicy.Deductible == 0)
                    {
                        lblDeductible.Text = Resources.CarInsurance.Option_No;
                    }
                    else if (_carpolicy.Deductible != -1 && _carpolicy.Deductible != 0)
                    {
                        lblDeductible.Text = Resources.CarInsurance.Option_Yes;
                    }

                    lblIncludeCTPL.Text = Resources.CarInsurance.Option_No;
                    if (_carpolicy.IsCTPL)
                    {
                        lblIncludeCTPL.Text = Resources.CarInsurance.Option_Yes;
                    }

                    trGarageType.Visible = false;
                    trProvinceofRegistration.Visible = false;
                    trAnyClaimLastYear.Visible = false;
                    trDeductible.Visible = false;
                    trAnyModification.Visible = false;
                    trIncludeCTPL.Visible = true;

                    switch (_carpolicy.InsuranceType)
                    {
                        case 0: //all classes
                            lblInsuranceType.Text = Resources.General.All;
                            trGarageType.Visible = true;
                            trDeductible.Visible = true;
                            trIncludeCTPL.Visible = true;
                            break;
                        case 10: //class 1
                            lblInsuranceType.Text = "1";
                            trGarageType.Visible = true;
                            trDeductible.Visible = true;
                            trIncludeCTPL.Visible = true;
                            break;
                        case 11: //class 1 (low cost)
                            lblInsuranceType.Text = "1+";
                            trGarageType.Visible = true;
                            trDeductible.Visible = true;
                            trIncludeCTPL.Visible = true;
                            break;
                        case 21: //class 2+
                            lblInsuranceType.Text = "2+";
                            trGarageType.Visible = true;
                            trDeductible.Visible = true;
                            trIncludeCTPL.Visible = true;
                            break;
                        case 31: //class 3+
                            lblInsuranceType.Text = "3+";
                            trGarageType.Visible = true;
                            trDeductible.Visible = true;
                            trIncludeCTPL.Visible = true;
                            break;
                        case 30: //class 3
                            lblInsuranceType.Text = "3";
                            trGarageType.Visible = false;
                            trDeductible.Visible = false;
                            trIncludeCTPL.Visible = true;
                            break;
                    }
                    #endregion

                }
                else
                {
                    lblMessage.Text = "Car policy did not save successfully!";
                    lblMessage.ForeColor = System.Drawing.Color.Red;
                    return false;
                }

                CarDriver _cardriver = new CarDriver();
                CarDriverDB _cardriverdb = new CarDriverDB();

                if (rdoYesAddDriver.Checked == true)
                {
                    int _drivercount = Convert.ToInt32(ddlDriverCount.SelectedValue);
                    int _insertcount = 0;
                    _cardriverdb.UpdateAllStatus(_carId, _refceuserid);

                    for (int i = 1; i <= _drivercount; i++)
                    {
                        _cardriver.StepId = 1;
                        _cardriver.RerCEUserId = _refceuserid;
                        _cardriver.CECarId = _carId;
                        if (i == 1)
                        {
                            _cardriver.CarDriverId = Convert.ToInt64(hdnDriverId1.Value);
                            _cardriver.DOB = _dtDriverDOB1;
                            _cardriver.Status = "Active";
                        }
                        else if (i == 2)
                        {
                            _cardriver.CarDriverId = Convert.ToInt64(hdnDriverId2.Value);
                            _cardriver.DOB = _dtDriverDOB2;
                            _cardriver.Status = "Active";
                        }

                        _cardriver.ViewedDetailId = Convert.ToInt64(Session[General.ViewedDetailsId].ToString());
                        if (_cardriverdb.Insert(_cardriver) > 0)
                        {
                            _insertcount++;
                        }
                    }

                    _cardriverdb = null;
                    _cardriver = null;

                    if (_insertcount == _drivercount)
                    {
                        lblMessage.Text += "<br />All drivers are successfully saved!";
                        lblMessage.ForeColor = System.Drawing.Color.Blue;
                    }
                    else
                    {
                        lblMessage.Text += "<br />All drivers are did not saved!";
                        lblMessage.ForeColor = System.Drawing.Color.Red;
                        return false;
                    }
                }
                else
                {
                    _cardriverdb.UpdateAllStatus(_carId, _refceuserid);
                }

                _carpolicy = null;
                _carpolicydb = null;
            }

            return _policyresult > 0;
        }
        catch (Exception ex)
        {
            return false;
        }
    }

    private void GenerateServerSideCarModel(int CarMakeId)
    {
        CarDetailDB _cardeaildb = new CarDetailDB();
        Int64 _carmakecount = _cardeaildb.GetCarModelCount(CarMakeId);
        DataTable _dtCarModel = _cardeaildb.GetCarModel(CarMakeId);
        if (_dtCarModel != null)
        {
            if (_dtCarModel.Rows.Count > 0)
            {
                int _rowCount = _dtCarModel.Rows.Count;
                for (int i = 0; i < _rowCount; i++)
                {
                }
            }
        }
    }

    public bool ValidDate(Int32 Year, Int32 Month, Int32 Day)
    {
        bool _isValid = true;
        int daysInMonth = 0;
        string leap, monthValid, dayValid, yearValid;
        if (Year >= 0000)
        {
            yearValid = "yes";
        }
        else
        {
            yearValid = "no";
        }
        if (Year % 400 == 0)
        {
            leap = "yes";
        }
        else if (Year % 100 == 0)
        {
            leap = "no";
        }
        else if (Year % 4 == 0)
        {
            leap = "yes";
        }
        else
        {
            leap = "no";
        }

        switch (Month)
        {
            case 1: daysInMonth = 31;
                break;
            case 3: daysInMonth = 31;
                break;
            case 4: daysInMonth = 30;
                break;
            case 5: daysInMonth = 31;
                break;
            case 6: daysInMonth = 30;
                break;
            case 7: daysInMonth = 31;
                break;
            case 8: daysInMonth = 31;
                break;
            case 9: daysInMonth = 30;
                break;
            case 10: daysInMonth = 31;
                break;
            case 11: daysInMonth = 30;
                break;
            case 12: daysInMonth = 31;
                break;
        }

        if (Month >= 1 && Month <= 12)
        {
            monthValid = "yes";
        }
        else
        {
            monthValid = "no";
        }
        if (Month == 2)
        {
            if (leap == "no")
            {
                daysInMonth = 28;
            }
            else if (leap == "yes")
            {
                daysInMonth = 29;
            }
        }

        if (1 <= Day && Day <= daysInMonth)
        {
            dayValid = "yes";
        }

        else
        {
            dayValid = "no";
        }

        if ((dayValid == "yes") && (monthValid == "yes") && (yearValid == "yes"))
        {
            _isValid = true;
        }
        else
        {
            _isValid = false;
        }

        return _isValid;
    }

    private void ShowCarAndPolicyDetail(Int64 CarId, Int64 PolicyId, Int64 UserId)
    {
        CarDetailTH _cardetail = new CarDetailTH();
        CarDetailTHDB _cardetaildb = new CarDetailTHDB();
        _cardetail = _cardetaildb.GetCar(CarId, UserId);

        CarPolicy _carpolicy = new CarPolicy();
        CarPolicyDB _carpolicydb = new CarPolicyDB();
        _carpolicy = _carpolicydb.GetCarPolicy(CarId, PolicyId, UserId);

        if (_carpolicy != null && _cardetail != null)
        {
            SetProperty(_carpolicy, _cardetail);
        }

        _cardetail = null;
        _cardetaildb = null;

        _carpolicy = null;
        _carpolicydb = null;
    }

    private void SetProperty(CarPolicy _CarPolicy, CarDetailTH _CarDetail)
    {
        ddlInsuranceType.Text = _CarPolicy.InsuranceType.ToString();

        if (ddlInsuranceType.Items[0].Value == "0")
        {
            ddlInsuranceType.SelectedIndex = 0;
            lblInsuranceType.Text = Resources.General.All;
        }

        ddlGarageType.Text = _CarPolicy.GarageType.ToString();
        LoadManufactYearList();

        ddlManufactYear.SelectedIndex = ddlManufactYear.Items.IndexOf(ddlManufactYear.Items.FindByValue(_CarDetail.ManufactYear.ToString()));
        ddlManufactYear_SelectedIndexChanged(null, null);
        ddlCarMake.Text = _CarDetail.CarMakeName;
        ddlCarMake_SelectedIndexChanged(null, null);
        string _tempDesc = _CarDetail.CarModelName + " " + _CarDetail.Body + " " + _CarDetail.CC + "cc " + _CarDetail.Door.ToString() + " doors";

        ddlModelBodyCCDoor.SelectedValue = _tempDesc;
        ddlModelBodyCCDoor_SelectedIndexChanged(null, null);
        hidCurInsuranceCompany.Value = _CarDetail.Info1;
        hidCurrentInsurer.Value = _CarPolicy.CurrentInsurer;
        txtGroupNo.Text = _CarDetail.GroupNo.ToString();
        lblCarVehicleType.Text = _CarDetail.Info2;
        //ChangeVehicleUsageList(lblCarVehicleType.Text);
        if (_CarDetail.Info3 == "110" || _CarDetail.Info3 == "210" || _CarDetail.Info3 == "320")
        {
            ddlVehicleType.Text = "110";
        }
        else
        {
            ddlVehicleType.Text = "120";
        }
        ddlVehicleType_SelectedIndexChanged(null, null);
        txtSumInsured.Text = _CarPolicy.SumInsured.ToString();
        lblSumInsured.Text = Convert.ToInt32(txtSumInsured.Text).ToString("#,000");

        rdoYesAccMod.Checked = _CarPolicy.IsAddAccMod;
        rdoNoAccMod.Checked = !_CarPolicy.IsAddAccMod;

        if (rdoYesAccMod.Checked)
        {
            txtNewSumInsured.Text = (_CarPolicy.SumInsured + _CarPolicy.AddAccModAmount).ToString();
            txtAccModAmount.Text = _CarPolicy.AddAccModAmount.ToString();
            lblSumInsured.Text = Convert.ToInt32(txtNewSumInsured.Text).ToString("#,000");
        }

        string _deductible = "";
        _deductible = _CarPolicy.Deductible.ToString();
        if (ddlInsuranceType.SelectedValue == "0" || ddlInsuranceType.SelectedValue == "10" || ddlInsuranceType.SelectedValue == "11" ||
            ddlInsuranceType.SelectedValue == "21" || ddlInsuranceType.SelectedValue == "31")
        {
            _deductible = _CarPolicy.Deductible.ToString();
            if (_CarPolicy.Deductible == 2000)
            {
                _deductible = "5000";
            }
        }
        else
        {
            _deductible = "0";
        }
        ddlDeduct.SelectedIndex = ddlDeduct.Items.IndexOf(ddlDeduct.Items.FindByValue(_deductible)); //Convert.ToInt32(_CarPolicy.Deductible) == 0 ? "0" : "-1";

        hidCoverageCommenceDate.Value = _CarPolicy.CoverageCommenceDate.Day.ToString("00") + _CarPolicy.CoverageCommenceDate.Month.ToString("00") + _CarPolicy.CoverageCommenceDate.Year.ToString("0000");
        rdoYesClaimLastYear.Checked = _CarPolicy.IsClaimLastYear;
        rdoNoClaimLastYear.Checked = !_CarPolicy.IsClaimLastYear;
        if (rdoYesClaimLastYear.Checked)
        {
            int NCB = _CarPolicy.NCDPercent;
            if (ddlNCB.Items.Count > 3 && NCB <= 20)
            {
                hidNCBClaim.Value = "1";
            }
        }

        rdoYesAddDriver.Checked = _CarPolicy.IsAddDriver;
        rdoYesAddDriver_CheckedChanged(null, null);
        rdoNoAddDriver.Checked = !_CarPolicy.IsAddDriver;
        ddlDriverCount.Text = _CarPolicy.NoOfDriver.ToString();
        rdoYesCTPL.Checked = _CarPolicy.IsCTPL;
        rdoNoCTPL.Checked = !_CarPolicy.IsCTPL;
        ddlNCB.Text = _CarPolicy.NCDPercent.ToString();

        if (_CarPolicy.NoOfDriver > 0 && rdoYesAddDriver.Checked)
        {
            divAddDriver.Visible = true;
            pnlDriver.Visible = true;
            txtAddDriver.Text = "1";

            int _noOfDriver = _CarPolicy.NoOfDriver;
            CarDriverList _cardriverlist = new CarDriverList();
            CarDriverDB _cardriverdb = new CarDriverDB();
            _cardriverlist = _cardriverdb.GetCarDriverList(_CarPolicy.CECarId, _CarPolicy.RefCEUserId);
            _cardriverdb = null;

            for (int i = 1; i <= _noOfDriver; i++)
            {
                CarDriver _cardriver = _cardriverlist[i - 1];
                if (i == 1)
                {
                    hdnDriverId1.Value = _cardriver.CarDriverId.ToString();
                    ddlDriver1Day.Text = _cardriver.DOB.Day.ToString();
                    ddlDriver1Month.Text = _cardriver.DOB.Month.ToString();
                    ddlDriver1Year.Text = _cardriver.DOB.Year.ToString();
                }
                else if (i == 2)
                {
                    hdnDriverId2.Value = _cardriver.CarDriverId.ToString();
                    ddlDriver2Day.Text = _cardriver.DOB.Day.ToString();
                    ddlDriver2Month.Text = _cardriver.DOB.Month.ToString();
                    ddlDriver2Year.Text = _cardriver.DOB.Year.ToString();
                }
            }
            _cardriverlist = null;
        }
        else
        {
            pnlDriver.Visible = false;
            divAddDriver.Visible = false;
            txtAddDriver.Text = "1";
        }
    }

    private void DriverSetting()
    {
        divDriver1.Visible = false;
        rfvDriver1Day.Enabled = false;
        rfvDriver1Month.Enabled = false;
        rfvDriver1Year.Enabled = false;

        divDriver2.Visible = false;
        rfvDriver2Day.Enabled = false;
        rfvDriver2Month.Enabled = false;
        rfvDriver2Year.Enabled = false;
        if (Convert.ToInt32(ddlInsuranceType.Text) == 10)
        {
            //divDriver1.Visible = true;
            if (rdoYesAddDriver.Checked)
            {
                int _drivercount = Convert.ToInt32(ddlDriverCount.SelectedValue);
                //divDriver1.Visible = true;
                if (_drivercount == 1)
                {
                    divDriver1.Visible = true;
                    rfvDriver1Day.Enabled = true;
                    rfvDriver1Month.Enabled = true;
                    rfvDriver1Year.Enabled = true;

                    divDriver2.Visible = false;
                    rfvDriver2Day.Enabled = false;
                    rfvDriver2Month.Enabled = false;
                    rfvDriver2Year.Enabled = false;
                }
                else if (_drivercount == 2)
                {
                    divDriver1.Visible = true;
                    rfvDriver1Day.Enabled = true;
                    rfvDriver1Month.Enabled = true;
                    rfvDriver1Year.Enabled = true;

                    divDriver2.Visible = true;
                    rfvDriver2Day.Enabled = true;
                    rfvDriver2Month.Enabled = true;
                    rfvDriver2Year.Enabled = true;
                }
            }
            else
            {
                divDriver1.Visible = false;
                rfvDriver1Day.Enabled = false;
                rfvDriver1Month.Enabled = false;
                rfvDriver1Year.Enabled = false;

                divDriver2.Visible = false;
                rfvDriver2Day.Enabled = false;
                rfvDriver2Month.Enabled = false;
                rfvDriver2Year.Enabled = false;
            }
        }
        /*
        if (rdoYesAddDriver.Checked)
        {
            int _drivercount = Convert.ToInt32(ddlDriverCount.SelectedValue);
            for (int i = 1; i <= 2; i++)
            {
                string strDivName = "divDriver" + i.ToString();
                HtmlGenericControl _divDriver = (HtmlGenericControl)pnlDriver.FindControl(strDivName);
                if (i > _drivercount)
                {
                    if (_divDriver != null)
                    {
                        _divDriver.Visible = false;
                    }
                }
                else
                {
                    if (_divDriver != null)
                    {
                        _divDriver.Visible = true;
                    }
                }
            }
        }
        else
        {
            for (int i = 2; i <= 2; i++)
            {
                string strDivName = "divDriver" + i.ToString();
                HtmlGenericControl _divDriver = (HtmlGenericControl)pnlDriver.FindControl(strDivName);
                string strUsrDriver = "UsrCarDriver" + i.ToString();
                if (_divDriver != null)
                {
                    _divDriver.Visible = false;
                    rfvDriver2Day.Enabled = false;
                    rfvDriver2Month.Enabled = false;
                    rfvDriver2Year.Enabled = false;

                }

            }
        }*/
    }

    private void OtherValidation()
    {
        if (rdoYesClaimLastYear.Checked == false && rdoNoClaimLastYear.Checked == false)
        {
            rfvAnyClaim.IsValid = false;
        }
        else
        {
            txtAnyClaim.Text = "1";
            rfvAnyClaim.Validate();
        }

        if (rdoYesAccMod.Checked == false && rdoNoAccMod.Checked == false)
        {
            rfvAccMod.IsValid = false;
        }
        else
        {
            if (rdoYesAccMod.Checked)
            {
                rfvAccModAmount.Validate();
                revAccModAmount.Validate();
                csvAccModAmount.Validate();
            }
            else
            {
                rfvAccModAmount.Enabled = false;
                revAccModAmount.Enabled = false;
                csvAccModAmount.Enabled = false;
                txtAccModAmount.Text = "0";
            }
            txtAccMod.Text = "1";
            rfvAccMod.Validate();
        }
    }

    private int GetExistingNCD()
    {
        int ExistingNCD = 0;

        if (ddlNCB.Text == "0")
            ExistingNCD = -1;
        else
            ExistingNCD = Convert.ToInt32(ddlNCB.Text) - 10;
        return ExistingNCD;
    }

    protected void rdoYesAddDriver_CheckedChanged(object sender, EventArgs e)
    {
        if (rdoYesAddDriver.Checked)
        {
            rdoNoAddDriver.Checked = false;
            txtAddDriver.Text = "1";
            pnlDriver.Visible = true;
            divAddDriver.Visible = true;

            //if (!Page.IsPostBack)
            DriverSetting();
        }
    }

    protected void rdoNoAddDriver_CheckedChanged(object sender, EventArgs e)
    {
        if (rdoNoAddDriver.Checked)
        {
            rdoYesAddDriver.Checked = false;
            txtAddDriver.Text = "1";
            pnlDriver.Visible = false;
            divAddDriver.Visible = false;

            //if (!Page.IsPostBack)
            DriverSetting();

        }

    }

    protected void rdoNoCliam_CheckChange(object sender, EventArgs e)
    {
        txtAnyClaim.Text = "1";
        ddlNCB.Items.Clear();
        ddlNCB.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
        ddlNCB.Items.Add(new ListItem("0 %", "0"));
        //ddlNCB.Items.Add(new ListItem("10", "10"));
        ddlNCB.Items.Add(new ListItem("20 %", "20"));
        ddlNCB.Items.Add(new ListItem("30 %", "30"));
        ddlNCB.Items.Add(new ListItem("40 %", "40"));
        ddlNCB.Items.Add(new ListItem("50 %", "50"));
    }

    protected void CheckClaim(object sender, EventArgs e)
    {
        ddlNCB.Items.Clear();
        ddlNCB.Items.Add(new ListItem("No NCD", "0"));
    }

    private void ChangeVehicleUsageList(string CarVehicleType)
    {
        ddlVehicleType.Items.Clear();
        ddlVehicleType.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
        if (CarVehicleType == "PU")
        {
            ddlVehicleType.Items.Add(new ListItem(Resources.CarInsurance.VehicleType_Private, "110"));
        }
        else
        {
            ddlVehicleType.Items.Add(new ListItem(Resources.CarInsurance.VehicleType_Private, "110"));
            ddlVehicleType.Items.Add(new ListItem(Resources.CarInsurance.VehicleType_Commercial, "120"));
        }
        rdoNoAddDriver.Checked = false;
        rdoYesAddDriver.Checked = false;
        divSpecifyDriver.Visible = false;
        divAddDriver.Visible = false;
    }

    private void GetCarMakeList(string Year, DropDownList ddlList)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblMake");
        SortedList _spList = new SortedList();
        _spList.Add("@Year", Year);
        _dt = _db.GetDataTableBySP("sprocGetCarMakeTHListByYear", _spList);
        ddlList.Items.Clear();
        ddlList.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
        if (_dt != null && _dt.Rows.Count > 0)
        {
            for (int i = 0; i < _dt.Rows.Count; i++)
            {
                ddlList.Items.Add(new ListItem(_dt.Rows[i][1].ToString(), _dt.Rows[i][0].ToString()));
            }
        }

        _dt = null;
        _db = null;
    }

    private void GetCarModelDescList(string CarMake, string Year, DropDownList ddlList)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblModelDesc");
        SortedList _spList = new SortedList();
        _spList.Add("@CarMake", CarMake);
        _spList.Add("@Year", Year);
        _dt = _db.GetDataTableBySP("sprocGetCarModelDescTHListByCarMakeCode", _spList);
        ddlList.Items.Clear();
        ddlModelBodyCCDoor.Items.Clear();
        ddlModelBodyCCDoor.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
        if (_dt != null && _dt.Rows.Count > 0)
        {
            ddlModelBodyCCDoor.DataSource = _dt;
            ddlModelBodyCCDoor.DataValueField = "CarModelDesc";
            ddlModelBodyCCDoor.DataTextField = "CarModelDisplay";
            ddlModelBodyCCDoor.DataBind();
            ddlModelBodyCCDoor.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
        }
        else
        {
            ddlList.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
        }
        _dt = null;
        _db = null;
    }

    private void GetCarModelSumInsuredAmountAndVehicleType(string CarMake, string CarModel, string Body, string CC, string Door, string Year, TextBox txtTextBox, Label lblLabel, Label lblLabelTwo)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblModelBody");
        SortedList _spList = new SortedList();
        _spList.Add("@CarMake", CarMake);
        _spList.Add("@CarModel", CarModel);
        _spList.Add("@Body", Body);
        _spList.Add("@CC", CC);
        _spList.Add("@Door", Door);
        _spList.Add("@Year", Year);
        _dt = _db.GetDataTableBySP("sprocGetCarModelSumInsuredAndVehicleTypeTHListByYear", _spList);
        if (_dt != null && _dt.Rows.Count > 0)
        {
            txtTextBox.Text = _dt.Rows[0][0].ToString();
            lblLabelTwo.Text = _dt.Rows[0][1].ToString();
            lblLabel.Text = Convert.ToInt32(txtTextBox.Text).ToString("#,000");
        }
        else
        {
            txtTextBox.Text = "0";
            lblLabel.Text = "0";
        }
        txtTextBox.ReadOnly = true;
        _dt = null;
        _db = null;
    }

    private void GetCarModelGroupNo(string CarMake, string CarModel, string Body, string CC, string Door, TextBox txtTextBox)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblModelBody");
        SortedList _spList = new SortedList();
        _spList.Add("@CarMake", CarMake);
        _spList.Add("@CarModel", CarModel);
        _spList.Add("@Body", Body);
        _spList.Add("@CC", CC);
        _spList.Add("@Door", Door);
        _dt = _db.GetDataTableBySP("sprocGetCarModelGroupTH", _spList);

        if (_dt != null && _dt.Rows.Count > 0)
        {
            txtTextBox.Text = _dt.Rows[0][0].ToString();
        }
        else
        {
            txtGroupNo.Text = "-1";
        }
        txtTextBox.ReadOnly = true;
        _dt = null;
        _db = null;
    }

    private void LoadManufactYearList()
    {
        int _yearCount = 9;

        ddlManufactYear.Items.Clear();

        if (ddlInsuranceType.Text != "-1")
        {
            _yearCount = 19;
            int _startYear = General.GetUTCDateTime().Year - _yearCount;
            int _endYear = General.GetUTCDateTime().Year;
            for (int i = _endYear; i >= _startYear; i--)
            {
                if (System.Globalization.CultureInfo.CurrentCulture.Name != "th-TH")
                {
                    ddlManufactYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
                }
                else
                {
                    ddlManufactYear.Items.Add(new ListItem(i.ToString() + " - พ.ศ. " + (i + 543).ToString(), i.ToString()));
                }
            }
        }
        ddlManufactYear.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
    }

    protected void CheckAccModAmount(object sender, ServerValidateEventArgs e)
    {
        e.IsValid = true;
    }

    private void LoadDOB()
    {
        ddlDriver1Day.Items.Clear();
        ddlDriver2Day.Items.Clear();
        for (int _day = 1; _day <= 31; _day++)
        {
            ddlDriver1Day.Items.Add(new ListItem(_day.ToString("00"), _day.ToString("00")));
            ddlDriver2Day.Items.Add(new ListItem(_day.ToString("00"), _day.ToString("00")));
        }
        ddlDriver1Day.Items.Insert(0, new ListItem(Resources.General.Day, "-1"));
        ddlDriver2Day.Items.Insert(0, new ListItem(Resources.General.Day, "-1"));

        ddlDriver1Year.Items.Clear();
        ddlDriver2Year.Items.Clear();
        int _styr = CE.Global.General.GetUTCDateTime().Year - 18;
        int _endyr = _styr - 70;
        for (int _year = _styr; _year >= _endyr; _year--)
        {
            ddlDriver1Year.Items.Add(new ListItem(_year.ToString(), _year.ToString()));
            ddlDriver2Year.Items.Add(new ListItem(_year.ToString(), _year.ToString()));
        }
        ddlDriver1Year.Items.Insert(0, new ListItem(Resources.General.Year, "-1"));
        ddlDriver2Year.Items.Insert(0, new ListItem(Resources.General.Year, "-1"));
    }

    private void LoadOccupation()
    {
        DataTable dtOccupation = General.GetComboItem(Resources.General.OccupationList, Resources.General.OccupationSortBy, true);
        ddlOccupation.DataSource = dtOccupation;
        ddlOccupation.DataTextField = dtOccupation.Columns[0].ColumnName.ToString();
        ddlOccupation.DataValueField = dtOccupation.Columns[1].ColumnName.ToString();
        ddlOccupation.DataBind();
        ddlOccupation.Items.Insert(0, new ListItem(Resources.General.Select, "-1"));
    }

    private void SetProviderMoreInfo(string _companyId, Label Header, Label Description)
    {
        string strPromoDes = string.Empty;
        if (_companyId == "11")
        {
            Header.Text = Resources.MoreInfo.AZCP_Title; // "Allianz C.P";
            strPromoDes = Resources.MoreInfo.AZCP_Line1;
            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.AZCP_Line2;
            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.AZCP_Line3;
            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.AZCP_Line4;
        }
        else if (_companyId == "12")
        {
            //Header.Text = "MSIG";
            Header.Text = Resources.MoreInfo.MSIG_Title;
            strPromoDes = Resources.MoreInfo.MSIG_Line1;
            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.MSIG_Line2;
            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.MSIG_Line3;
            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.MSIG_Line4;
        }
        else if (_companyId == "16")
        {
            //Header.Text = "AXA";
            Header.Text = Resources.MoreInfo.AXA_Title;
            strPromoDes = Resources.MoreInfo.AXA_Line1;
            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.AXA_Line2;
            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.AXA_Line3;
            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.AXA_Line4;
        }
        else if (_companyId == "29")
        {
            //Header.Text = "LMG Insurance";
            Header.Text = Resources.MoreInfo.LMG_Title;

            if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
            {
                strPromoDes = Resources.MoreInfo.LMG_Line1;
            }
            else
            {
                strPromoDes = "LMG Insurance Co. Ltd, previously named Narai International Insurance Co. Ltd, "
                + "was established on 27 November 1975. In 2003 the company merged with Kum Klao Insurance Public Co. Ltd and registered under the new name of LMG Insurance Co. Ltd "
                + "on 6 September 2004.";
            }

            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.LMG_Line2;
            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.LMG_Line3;
            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.LMG_Line4;
        }
        else if (_companyId == "31")
        {
            //Header.Text = "Chartis";
            Header.Text = Resources.MoreInfo.Chartis_Title;
            strPromoDes = Resources.MoreInfo.Chartis_Line1;
            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.Chartis_Line2;
            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.Chartis_Line3;
            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.Chartis_Line4;
        }
        else if (_companyId == "32")
        {
            //Header.Text = "Bangkok Insurance";
            Header.Text = Resources.MoreInfo.BKI_Title;
            strPromoDes = Resources.MoreInfo.BKI_Line1;
            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.BKI_Line2;
            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.BKI_Line3;
            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.BKI_Line4;
        }
        else if (_companyId == "33")
        {
            Header.Text = Resources.MoreInfo.MuangThai_Title;
            strPromoDes = Resources.MoreInfo.MuangThai_Line1;
            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.MuangThai_Line2;

        }
        else if (_companyId == "35")
        {
            Header.Text = Resources.MoreInfo.KPI_Title;
            strPromoDes = Resources.MoreInfo.KPI_Line1;
            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.KPI_Line2;

        }
        else if (_companyId == "39")
        {
            Header.Text = Resources.MoreInfo.Mittare_Title;
            strPromoDes = Resources.MoreInfo.Mittare_Line1;
            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.Mittare_Line2;

        }
        else if (_companyId == "41")
        {
            Header.Text = Resources.MoreInfo.KSK_Title;
            strPromoDes = Resources.MoreInfo.KSK_Line1;
            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.KSK_Line2;
        }
        else if (_companyId == "43")
        {
            Header.Text = Resources.MoreInfo.SMK_Title;
            strPromoDes = Resources.MoreInfo.SMK_Line1;
            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.SMK_Line2;

        }
        else if (_companyId == "45")
        {
            Header.Text = Resources.MoreInfo.Viriyah_Title;
            strPromoDes = Resources.MoreInfo.Viriyah_Line1;
            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.Viriyah_Line2;

        }
        else if (_companyId == "46")
        {
            Header.Text = Resources.MoreInfo.Tokio_Title;
            strPromoDes = Resources.MoreInfo.Tokio_Line1;
            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.Tokio_Line2;
            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.Tokio_Line3;
        }
        else if (_companyId == "51")
        {
            Header.Text = Resources.MoreInfo.SCSMG_Title;
            strPromoDes = Resources.MoreInfo.SCSMG_Line1;
            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.SCSMG_Line2;

        }
        else if (_companyId == "58")
        {
            Header.Text = Resources.MoreInfo.Thaivivat_Title;
            strPromoDes = Resources.MoreInfo.Thaivivat_Line1;
            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.Thaivivat_Line2;

        }
        else if (_companyId == "65")
        {
            Header.Text = Resources.MoreInfo.Dhipaya_Title;
            strPromoDes = Resources.MoreInfo.Dhipaya_Line1;
            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.Dhipaya_Line2;

        }
        else if (_companyId == "66")
        {
            Header.Text = Resources.MoreInfo.Thaipaiboon_Title;
            strPromoDes = Resources.MoreInfo.Thaipaiboon_Line1;
            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.Thaipaiboon_Line2;

        }
        else if (_companyId == "67")
        {
            Header.Text = Resources.MoreInfo.Deves_Title;
            strPromoDes = Resources.MoreInfo.Deves_Line1;
            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.Deves_Line2;

        }
        else if (_companyId == "68")
        {
            Header.Text = Resources.MoreInfo.Thaisri_Title;
            strPromoDes = Resources.MoreInfo.Thaisri_Line1;
            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.Thaisri_Line2;

        }
        else if (_companyId == "69")
        {
            Header.Text = Resources.MoreInfo.Asset_Title;
            strPromoDes = Resources.MoreInfo.Asset_Line1;
            strPromoDes = strPromoDes + "<br/> <br/>";
            strPromoDes = strPromoDes + Resources.MoreInfo.Asset_Line2;

        }
        Description.Text = strPromoDes;
    }

    private string getProviderLogoCss(string _companyId, string _type)
    {
        string _class = string.Empty;
        if (_type == "result")
        {
            if (_companyId == "11")
            {
                _class = "allianz-logo";
            }
            else if (_companyId == "12")
            {
                _class = "msig-logo";
            }
            else if (_companyId == "16")
            {
                _class = "axa-logo";
            }
            else if (_companyId == "29")
            {
                _class = "lmg-logo";
            }
            else if (_companyId == "31")
            {
                _class = "aig-logo";
            }
            else if (_companyId == "32")
            {
                _class = "bangkok-insurance-logo";
            }
            else if (_companyId == "33")
            {
                _class = "muangthai-logo";

            }
            else if (_companyId == "35")
            {
                _class = "krungthai-logo";

            }
            else if (_companyId == "39")
            {
                _class = "mittare-logo";

            }
            else if (_companyId == "41")
            {
                _class = "ksk-logo";
            }
            else if (_companyId == "43")
            {
                _class = "synmunkong-logo";

            }
            else if (_companyId == "45")
            {
                _class = "viriyah-logo";

            }
            else if (_companyId == "46")
            {
                _class = "tokiomarine-logo";
            }
            else if (_companyId == "51")
            {
                _class = "scsmg-logo";

            }
            else if (_companyId == "58")
            {
                _class = "thaivivat-logo";

            }
            else if (_companyId == "65")
            {
                _class = "dhipaya-logo";

            }
            else if (_companyId == "66")
            {
                _class = "thaipaiboon-logo";

            }
            else if (_companyId == "67")
            {
                _class = "deves-logo";

            }
            else if (_companyId == "68")
            {
                _class = "thaisri-logo";

            }
            else if (_companyId == "69")
            {
                _class = "asset-logo";

            }
        }
        else if (_type == "moreinfo")
        {
            if (_companyId == "11")
            {
                _class = "allianz";
            }
            else if (_companyId == "12")
            {
                _class = "msig";
            }
            else if (_companyId == "16")
            {
                _class = "axa";
            }
            else if (_companyId == "29")
            {
                _class = "lmg";
            }
            else if (_companyId == "31")
            {
                _class = "aig";
            }
            else if (_companyId == "32")
            {
                _class = "bangkok-insurance";
            }
            else if (_companyId == "33")
            {
                _class = "muangthai";

            }
            else if (_companyId == "35")
            {
                _class = "krungthai";

            }
            else if (_companyId == "39")
            {
                _class = "mittare";

            }
            else if (_companyId == "41")
            {
                _class = "ksk";
            }
            else if (_companyId == "43")
            {
                _class = "synmunkong";

            }
            else if (_companyId == "45")
            {
                _class = "viriyah";

            }
            else if (_companyId == "46")
            {
                _class = "tokiomarine";
            }
            else if (_companyId == "51")
            {
                _class = "scsmg";

            }
            else if (_companyId == "58")
            {
                _class = "thaivivat";

            }
            else if (_companyId == "65")
            {
                _class = "dhipaya";

            }
            else if (_companyId == "66")
            {
                _class = "thaipaiboon";

            }
            else if (_companyId == "67")
            {
                _class = "deves";

            }
            else if (_companyId == "68")
            {
                _class = "thaisri";

            }
            else if (_companyId == "69")
            {
                _class = "asset";

            }
        }
        return _class;
    }

    private void ControlVisibleOnOff()
    {
        switch (Convert.ToInt32(ddlInsuranceType.Text))
        {
            case 0:
            case 10:
                divGarageType.Style.Add("display", "");
                divDeduct.Style.Add("display", "");
                //divAnyClaimLastYear.Style.Add("display", "");
                divDriver.Style.Add("display", "none");
                divYesAccMod.Style.Add("display", "none");
                //divCTPL.Style.Add("display", "none");
                divCTPL.Style.Add("display", "");
                break;
            case 21:
            case 31:
                divGarageType.Style.Add("display", "");
                divDeduct.Style.Add("display", "");
                //divAnyClaimLastYear.Style.Add("display", "none");
                divDriver.Style.Add("display", "none");
                divYesAccMod.Style.Add("display", "none");
                //divCTPL.Style.Add("display", "none");
                divCTPL.Style.Add("display", "");
                break;
            case 30:
                divCTPL.Style.Add("display", "");
                divGarageType.Style.Add("display", "none");
                //divAnyClaimLastYear.Style.Add("display", "none");
                divDriver.Style.Add("display", "none");
                divYesAccMod.Style.Add("display", "none");
                divDeduct.Style.Add("display", "none");
                break;
        }
    }

    #region YourDetail

    CE.User.Profile _profile = null;
    CE.User.ProfileDB _profiledb = null;
    Contact _contact = null;
    ContactDB _contactdb = null;
    private void ShowCustomerDetailByCar(Int64 CarId)
    {
        CarDetailTH _cardetail = new CarDetailTH();
        CarDetailTHDB _cardetaildb = new CarDetailTHDB();

        _cardetail = _cardetaildb.GetCar(CarId, 0);
        if (_cardetail != null)
        {
            if (_cardetail.Info5.Length > 0 &&
                _cardetail.Info6.Length > 0 &&
                _cardetail.Info7.Length > 0 &&
                _cardetail.Info8.Length > 0 &&
                _cardetail.Info9.Length > 0 &&
                _cardetail.Info10.Length > 0 &&
                _cardetail.Info11.Length > 0 &&
                _cardetail.Info12.Length > 0 &&
                _cardetail.Info13.Length > 0 &&
                _cardetail.Info14.Length > 0)
            {
                txtEmailAddress.Text = _cardetail.Info5;
                txtMobile.Text = _cardetail.Info6;
                if (_cardetail.Info8.Length > 0)
                {
                    txtName.Text = _cardetail.Info8 + (_cardetail.Info7.Trim() != "" ? " " + _cardetail.Info7.Trim() : "");
                    txtNamePop.Text = _cardetail.Info8 + (_cardetail.Info7.Trim() != "" ? " " + _cardetail.Info7.Trim() : "");
                }
                ddlOccupation.Text = _cardetail.Info11;
            }
            else
            {
                if (Session[General.UserId] != null)
                {
                    ShowCustomerDetail(Convert.ToInt64(Session[General.UserId].ToString()));
                }
            }
        }
    }

    private void ShowCustomerDetail(Int64 UserId)
    {
        _profile = new CE.User.Profile();
        _profiledb = new ProfileDB();
        _contact = new Contact();
        _contactdb = new ContactDB();

        _profile = _profiledb.GetProfile(UserId);
        _profiledb = null;

        if (_profile != null)
        {
            txtName.Text = _profile.FirstName + (_profile.SurName.Trim() != "" ? " " + _profile.SurName : "");
            txtNamePop.Text = _profile.FirstName + (_profile.SurName.Trim() != "" ? " " + _profile.SurName : "");
            ddlOccupation.Text = _profile.Occupation.ToString();
            _contact = _contactdb.GetContact(UserId);
            if (_contact != null)
            {
                txtMobile.Text = _contact.Mobile;
                txtEmailAddress.Text = _contact.Email;
                txtEmailAddress.ReadOnly = true;
            }
            _profile = null;
        }
    }

    private Int64 UpdateCustomerDetailByCarId(Int64 UserId, Int64 CarId)
    {
        Int64 _retValue = 0;
        txtName.Text = CE.Global.General.ClearScriptTag(txtName.Text.Trim());
        if (UserId > 0 && CarId > 0)
        {
            CarDetailTH _cardetail = new CarDetailTH();
            CarDetailTHDB _cardetaildb = new CarDetailTHDB();
            _cardetail = _cardetaildb.GetCar(CarId, UserId);

            if (_cardetail != null)
            {
                _cardetail.Info5 = txtEmailAddress.Text;
                _cardetail.Info6 = txtMobile.Text.Trim();
                _cardetail.Info7 = "";
                if (txtName.Text.Trim().Length > 0)
                {
                    _cardetail.Info8 = Server.HtmlEncode(txtName.Text);
                }
                _cardetail.Info9 = "";
                _cardetail.Info10 = "";
                _cardetail.Info11 = ddlOccupation.Text;
                _cardetail.Info12 = "";
                _cardetail.Info13 = "";
                _cardetail.Info14 = "";
                _cardetail.Info15 = "";
                _cardetail.RefCEUserId = UserId;
            }

            //RefUserId only update
            CarPolicy _carpolicy = new CarPolicy();
            CarPolicyDB _carpolicydb = new CarPolicyDB();
            _carpolicy = _carpolicydb.GetCarPolicy(CarId, UserId);
            _carpolicy.RefCEUserId = UserId;

            _retValue = _cardetaildb.Insert(_cardetail);

            _retValue = _carpolicydb.Insert(_carpolicy);

            //update RefIds
            CarDetailTHDB cardb = new CarDetailTHDB();
            cardb.UpdateCarDetailPolicy(CarId, UserId);

            if (_retValue <= 0)
            {
            }
        }

        return _retValue;
    }

    private Int64 UpdateProfile(Int64 UserId, Int64 CarId)
    {
        Int64 _retValue = 0;

        if (UserId != 0)
        {
            Profile _profile = new Profile();
            ProfileDB _profiledb = new ProfileDB();

            Contact _contact = new Contact();
            ContactDB _contactdb = new ContactDB();

            _profile = _profiledb.GetProfile(UserId);
            _contact = _contactdb.GetContact(UserId);
            _retValue = UserId;
            if (_profile != null)
            {
                #region Update Profile

                //_profile.Salutation = "";
                _profile.FirstName = HttpUtility.HtmlEncode(txtNamePop.Text);
                //_profile.SurName = "";
                //if (_profile.DOB.Year == 1900)
                //{
                //    DateTime dteDOB = new DateTime(1995, 1, 1);
                //    _profile.DOB = dteDOB;
                //}
                //if (_profile.Gender.ToString().Trim() == "")
                //{
                //    _profile.Gender = 'M';
                //}
                _profile.Status = "Complete";

                _retValue = _profiledb.Insert(_profile);

                if (_contact != null)
                {
                    _contact.Mobile = txtMobilePop.Text.Trim();
                    _contact.Status = true;

                    _retValue = _contactdb.Insert(_contact);
                }

                if (_retValue > 0)
                {
                    if (_profile.FirstName != string.Empty)
                    {
                        Session[CE.Global.General.UserName] = _profile.FirstName + " " + _profile.SurName;
                    }
                    else
                    {
                        Session[CE.Global.General.UserName] = _profile.SurName;
                    }
                    if (_contact != null)
                    {
                        Session[General.UserPhoneNo] = _contact.Mobile;
                    }
                    Session[CE.Global.General.UserProfileAndContactComplete] = "1";
                    if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) == Convert.ToInt32(CE.Global.CEUserType.Provider))
                    {
                        Session[CE.Global.General.ProviderProfileFirstTime] = "0";
                    }
                    Session[CE.Global.General.IsAcceptTC] = "0";
                    if (_profile.IsAcceptTC == true)
                    {
                        Session[CE.Global.General.IsAcceptTC] = "1";
                    }
                }

                _profile = null;
                _contact = null;
                #endregion
            }
        }
        else
        {
            _retValue = SaveNewCustomer();
            UserId = _retValue;
        }

        if (_retValue > 0 && CarId > 0)
        {
            CarDetailTH _cardetail = new CarDetailTH();
            CarDetailTHDB _cardetaildb = new CarDetailTHDB();
            _cardetail = _cardetaildb.GetCar(CarId, UserId);


            Profile _profile = new CE.User.Profile();
            ProfileDB _profiledb = new ProfileDB();
            _profile = _profiledb.GetProfile(UserId);

            if (_cardetail != null)
            {
                _cardetail.Info5 = txtEmailPop.Text.Trim().ToLower();
                _cardetail.Info6 = txtMobilePop.Text.Trim();
                _cardetail.Info7 = ""; //txtSurName.Text.Trim();
                _cardetail.Info8 = Session[CE.Global.General.UserName].ToString();
                if (_profile.Gender.ToString().Trim() != "")
                {
                    _cardetail.Info9 = _profile.Gender.ToString();
                }
                else
                {
                    _cardetail.Info9 = "M";
                }
                if (_profile.DOB.Year == 1900)
                {
                    DateTime dteDOB = new DateTime(1995, 1, 1);
                    _cardetail.Info10 = dteDOB.ToString("dd-MMM-yyyy");
                }
                else
                {
                    _cardetail.Info10 = _profile.DOB.ToString("dd-MMM-yyyy");
                }
                _cardetail.Info11 = _profile.Occupation.ToString();
                _cardetail.Info12 = "";// ddlJobNature.GetJobNature();
                _cardetail.Info13 = "";// ddlMaritalStatus.GetMaritalStatus();
                _cardetail.Info14 = "";// ddlYearDriveSg.Text;
                _cardetail.Info15 = "";// ddlSalutation.GetSalutation();
                _cardetail.RefCEUserId = UserId;
            }
            _profile = null;

            //RefUserId only update
            CarPolicy _carpolicy = new CarPolicy();
            CarPolicyDB _carpolicydb = new CarPolicyDB();
            _carpolicy = _carpolicydb.GetCarPolicy(CarId, UserId);
            _carpolicy.RefCEUserId = UserId;

            _retValue = _cardetaildb.Insert(_cardetail);

            _retValue = _carpolicydb.Insert(_carpolicy);

            //update RefIds
            CarDetailTHDB cardb = new CarDetailTHDB();
            cardb.UpdateCarDetailPolicy(CarId, UserId);

            if (_retValue <= 0)
            {
            }
        }

        return _retValue;
    }

    private Int64 SaveNewCustomer()
    {
        #region New Customer
        Int64 _retVal = 0;
        if (Page.IsValid)
        {

            Account _useraccount = new Account();
            AccountDB _useraccountdb = new AccountDB();

            Profile _userprofile = new Profile();
            ProfileDB _userprofiledb = new ProfileDB();

            Contact _contact = new Contact();
            ContactDB _contactdb = new ContactDB();

            _useraccount = _useraccountdb.GetUserAccount(txtEmailPop.Text.Trim(), Convert.ToInt32(CE.Global.CEUserType.Customer));
            //Hide on 13 Nov 2014 //_useraccount = _useraccountdb.GetUserAccount(txtEmailPop.Text.Trim(), txtMobilePop.Text.Trim().ToLower(), Convert.ToInt32(CE.Global.CEUserType.Customer));
            //Hide on 23 Oct 2014 //if (_useraccountdb.IsAlreadyExist(txtUserEmail.Text.Trim().ToLower(), txtUserMobile.Text.Trim().ToLower(), Convert.ToInt32(CE.Global.CEUserType.Customer)))
            if (_useraccount != null)
            {
                //Hide on 23 Oct 2014 //_useraccount = _useraccountdb.GetUserAccount(txtUserEmail.Text.Trim(), txtUserMobile.Text.Trim().ToLower(), 400);
                if (_useraccount.CEID > 0)
                {
                    _retVal = _useraccount.CEID;
                    _contact = _contactdb.GetContact(_useraccount.CEID);
                    Session[CE.Global.General.UserId] = _useraccount.CEID;
                    Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
                    Session[CE.Global.General.UserEmail] = _useraccount.Email;
                    Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
                    Session[CE.Global.General.StartTime] = General.GetUTCDateTime().ToString();
                    _userprofile = _userprofiledb.GetProfile(_useraccount.CEID);
                    if (_userprofile != null && _userprofile.ProfileId > 0)
                    {
                        if (_userprofile.FirstName != string.Empty)
                        {
                            Session[CE.Global.General.UserName] = _userprofile.FirstName + " " + _userprofile.SurName;
                        }
                        else
                        {
                            Session[CE.Global.General.UserName] = _userprofile.SurName;
                        }
                    }
                }
            }
            else
            {
                long _result = -1;
                _useraccount = new Account();
                _useraccount.Email = txtEmailPop.Text.Trim().ToLower();
                string _authcode = txtMobilePop.Text.Trim();
                _useraccount.AuthCode = _authcode;
                _useraccount.UserId = "CEUSERAUTOIDCI";
                _useraccount.UserTypeId = Convert.ToInt32(CE.Global.CEUserType.Customer);
                _useraccount.IsAcceptTC = false;
                _useraccount.Status = true;
                _useraccount.RefCEUserID = -1;
                _result = _useraccountdb.Insert(_useraccount);
                _useraccount.CEID = _result;
                _retVal = _useraccount.CEID;
                if (_result > 0)
                {
                    _userprofile.Salutation = "";
                    _userprofile.FirstName = Server.HtmlEncode(txtNamePop.Text);
                    _userprofile.SurName = "";
                    DateTime dteDOB = new DateTime(1995, 1, 1);
                    _userprofile.DOB = dteDOB;
                    _userprofile.Gender = 'M';

                    _userprofile.Occupation = Convert.ToInt32("54");
                    _userprofile.Status = "Complete";
                    _userprofile.RefCEUserId = _useraccount.CEID;
                    _userprofile.IsAcceptTC = checkIsAgreement.Checked;
                    _result = _userprofiledb.Insert(_userprofile);

                    _contact.Email = _useraccount.Email;
                    _contact.Mobile = txtMobilePop.Text.Trim();

                    _contact.Status = true;
                    _contact.RefCEUserId = _useraccount.CEID;
                    _result = _contactdb.Insert(_contact);

                    if (_result > 0)
                    {
                        Session[CE.Global.General.UserId] = _useraccount.CEID;
                        Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
                        Session[CE.Global.General.UserEmail] = _useraccount.Email;
                        Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
                        Session[CE.Global.General.StartTime] = General.GetUTCDateTime().ToString();
                        if (_userprofile.FirstName != string.Empty)
                        {
                            Session[CE.Global.General.UserName] = _userprofile.FirstName + " " + _userprofile.SurName;
                        }
                        else
                        {
                            Session[CE.Global.General.UserName] = _userprofile.SurName;
                        }
                        Session[CE.Global.General.UserProfileAndContactComplete] = "1";
                        Session[CE.Global.General.IsAcceptTC] = "0";
                        if (_userprofile.IsAcceptTC == true)
                        {
                            Session[CE.Global.General.IsAcceptTC] = "1";
                        }
                    }
                }

            }
        }
        else
        {
            _retVal = 0;
        }

        return _retVal;
        #endregion
    }

    #region Hide on 23 Oct 2014
    //private Int64 UpdateProfile(Int64 UserId, Int64 CarId)
    //{
    //    Int64 _retValue = 0;
    //    txtName.Text = CE.Global.General.ClearScriptTag(txtName.Text.Trim());
    //    if (UserId != 0)
    //    {
    //        _profile = new CE.User.Profile();
    //        _profiledb = new ProfileDB();

    //        _contact = new Contact();
    //        _contactdb = new ContactDB();

    //        _profile = _profiledb.GetProfile(UserId);
    //        _contact = _contactdb.GetContact(UserId);

    //        if (_profile != null)
    //        {
    //            #region Update Profile

    //            _profile.Salutation = "";
    //            _profile.FirstName = Server.HtmlEncode(txtName.Text);
    //            _profile.SurName = "";
    //            _profile.Occupation = Convert.ToInt32(ddlOccupation.Text);
    //            _profile.Status = "Complete";

    //            _retValue = _profiledb.Insert(_profile);

    //            if (_retValue > 0 && _contact != null)
    //            {
    //                _contact.Mobile = txtMobile.Text.Trim();
    //                _contact.Status = true;

    //                _retValue = _contactdb.Insert(_contact);
    //            }
    //            else
    //            {
    //            }

    //            if (_retValue > 0)
    //            {
    //                if (_profile.FirstName != string.Empty)
    //                {
    //                    Session[CE.Global.General.UserName] = _profile.FirstName + " " + _profile.SurName;
    //                }
    //                else
    //                {
    //                    Session[CE.Global.General.UserName] = _profile.SurName;
    //                }
    //                Session[General.UserPhoneNo] = txtMobile.Text.Trim();
    //                Session[CE.Global.General.UserProfileAndContactComplete] = "1";
    //                if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
    //                    Convert.ToInt32(CE.Global.CEUserType.Provider))
    //                {
    //                    Session[CE.Global.General.ProviderProfileFirstTime] = "0";
    //                }
    //            }
    //            else
    //            {
    //            }

    //            _profile = null;
    //            _contact = null;
    //            #endregion
    //        }
    //    }
    //    else
    //    {
    //        _retValue = SaveNewCustomer();
    //        UserId = _retValue;
    //    }

    //    if (_retValue > 0)
    //    {
    //        CarDetailTH _cardetail = new CarDetailTH();
    //        CarDetailTHDB _cardetaildb = new CarDetailTHDB();
    //        _cardetail = _cardetaildb.GetCar(CarId, UserId);

    //        if (_cardetail != null)
    //        {
    //            _cardetail.Info5 = txtEmailAddress.Text;
    //            _cardetail.Info6 = txtMobile.Text.Trim();
    //            _cardetail.Info7 = "";
    //            if (txtName.Text.Trim().Length > 0)
    //            {
    //                _cardetail.Info8 = Server.HtmlEncode(txtName.Text);
    //            }
    //            _cardetail.Info9 = "";
    //            _cardetail.Info10 = "";
    //            _cardetail.Info11 = ddlOccupation.Text;
    //            _cardetail.Info12 = "";
    //            _cardetail.Info13 = "";
    //            _cardetail.Info14 = "";
    //            _cardetail.Info15 = "";
    //            _cardetail.RefCEUserId = UserId;
    //        }

    //        //RefUserId only update
    //        CarPolicy _carpolicy = new CarPolicy();
    //        CarPolicyDB _carpolicydb = new CarPolicyDB();
    //        _carpolicy = _carpolicydb.GetCarPolicy(CarId, UserId);
    //        _carpolicy.RefCEUserId = UserId;

    //        _retValue = _cardetaildb.Insert(_cardetail);

    //        _retValue = _carpolicydb.Insert(_carpolicy);

    //        //update RefIds
    //        CarDetailTHDB cardb = new CarDetailTHDB();
    //        cardb.UpdateCarDetailPolicy(CarId, UserId);

    //        if (_retValue <= 0)
    //        {
    //        }
    //    }

    //    return _retValue;
    //}

    //private Int64 SaveNewCustomer()
    //{
    //    #region New Customer
    //    Int64 _retVal = 0;
    //    if (Page.IsValid)
    //    {

    //        Account _useraccount = new Account();
    //        AccountDB _useraccountdb = new AccountDB();

    //        if (_useraccountdb.IsAlreadyExist(txtEmailAddress.Text.Trim(), Convert.ToInt32(CE.Global.CEUserType.Customer)))
    //        {
    //            txtEmailAddress.ControlStyle.CssClass = "validationError";
    //            _retVal = 0;
    //        }
    //        else
    //        {
    //            Profile _userprofile = new Profile();
    //            ProfileDB _userprofiledb = new ProfileDB();
    //            Contact _contact = new Contact();
    //            ContactDB _contactdb = new ContactDB();

    //            long _result = -1;
    //            _useraccount.Email = txtEmailAddress.Text.ToLower();
    //            string _authcode = txtMobile.Text.Trim();
    //            _useraccount.AuthCode = _authcode;
    //            _useraccount.UserId = "CEUSERAUTOIDCI";
    //            _useraccount.UserTypeId = Convert.ToInt32(CE.Global.CEUserType.Customer);
    //            _useraccount.IsAcceptTC = false;
    //            _useraccount.Status = true;
    //            _useraccount.RefCEUserID = -1;

    //            _result = _useraccountdb.Insert(_useraccount);
    //            _useraccount.CEID = _result;
    //            _retVal = _useraccount.CEID;

    //            if (_result > 0)
    //            {
    //                _userprofile.Salutation = "";
    //                _userprofile.FirstName = Server.HtmlEncode(txtName.Text);
    //                _userprofile.SurName = "";
    //                _userprofile.Gender = (char)' ';
    //                _userprofile.Occupation = Convert.ToInt32(ddlOccupation.Text);
    //                _userprofile.Status = "Complete";
    //                _userprofile.RefCEUserId = _useraccount.CEID;
    //                _userprofile.IsAcceptTC = checkIsAgreement.Checked;
    //                _result = _userprofiledb.Insert(_userprofile);
    //                _contact.Email = _useraccount.Email;
    //                _contact.Mobile = txtMobile.Text.Trim();
    //                _contact.Status = true;
    //                _contact.RefCEUserId = _useraccount.CEID;
    //                _result = _contactdb.Insert(_contact);

    //                if (_result > 0)
    //                {
    //                    SaveUserLoginInformation(_useraccount.CEID, _useraccount.UserTypeId);
    //                    Session[CE.Global.General.UserId] = _useraccount.CEID;
    //                    Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
    //                    Session[CE.Global.General.UserEmail] = _useraccount.Email;
    //                    Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
    //                    Session[CE.Global.General.StartTime] = General.GetUTCDateTime().ToString();
    //                    if (_userprofile.FirstName != string.Empty)
    //                    {
    //                        Session[CE.Global.General.UserName] = _userprofile.FirstName + " " + _userprofile.SurName;
    //                    }
    //                    else
    //                    {
    //                        Session[CE.Global.General.UserName] = _userprofile.SurName;
    //                    }
    //                    Session[CE.Global.General.UserProfileAndContactComplete] = "1";
    //                }

    //            }

    //        }
    //    }
    //    else
    //    {
    //        _retVal = 0;
    //    }

    //    return _retVal;
    //    #endregion
    //}
    #endregion

    private bool SendMailToUser(string EmailAddress, string UserName, string AuthCode)
    {
        bool _retVal = false;
        _retVal = CE.Email.Welcome.SendMail(EmailAddress, UserName, AuthCode);
        return _retVal;
    }

    protected bool SaveUserLoginInformation(Int64 CEID, int UserTypeId)
    {
        LoginHistory _loghis = new LoginHistory();
        LoginHistoryDB _loghisdb = new LoginHistoryDB();
        LoginInformation _loginfo = new LoginInformation();
        LoginInformationDB _loginfodb = new LoginInformationDB();

        _loghis.CEID = CEID;
        _loghis.UserTypeId = UserTypeId;
        _loghis.StartTime = General.GetUTCDateTime();
        _loghis.EndTime = General.GetUTCDateTime();
        _loghis.IsExpired = false;
        _loghis.Status = "LOGIN";

        _loghis.LoginHisId = _loghisdb.Insert(_loghis);

        if (_loghis.LoginHisId > 0)
        {
            Session[CE.Global.General.LoginHistoryId] = _loghis.LoginHisId.ToString();
            _loginfo.CEID = CEID;
            _loginfo.UserTypeId = UserTypeId;
            _loginfo.LogHisId = _loghis.LoginHisId;

            _loginfo.Browser = Request.Browser.Browser;
            _loginfo.BrowserType = Request.Browser.Type;
            _loginfo.BrowserVersion = Request.Browser.Version;
            _loginfo.MajorVersion = Request.Browser.MajorVersion.ToString();
            _loginfo.MinorVersion = Request.Browser.MinorVersionString;
            _loginfo.JavaScript = Request.Browser.JavaScript;
            _loginfo.VBScript = Request.Browser.VBScript;
            _loginfo.ActivX = Request.Browser.ActiveXControls;
            _loginfo.Frames = Request.Browser.Frames;
            _loginfo.Tables = Request.Browser.Tables;
            _loginfo.Cookies = Request.Browser.Cookies;
            _loginfo.DotNetVersion = Request.Browser.ClrVersion.ToString();
            _loginfo.JavaApplet = Request.Browser.JavaApplets;
            _loginfo.Win16 = Request.Browser.Win16;
            _loginfo.Win32 = Request.Browser.Win32;
            _loginfo.Platform = Request.Browser.Platform;
            _loginfo.UserAgent = Request.UserAgent.ToString();
            _loginfo.IpAddress = Request.UserHostAddress;
            _loginfo.HostName = Request.UserHostName;

            _loginfo.UserInfoId = _loginfodb.Insert(_loginfo);
        }

        return _loginfo.UserInfoId > 0;

    }

    #endregion

    private void SetCookies(string UserName, string UserEmail, string UserMobile)
    {
        try
        {
            HttpCookie _cookie = new HttpCookie("GGQuote");
            _cookie.Values.Add("CustomerName", MySecurity.Encrypt(UserName, true));
            _cookie.Values.Add("CustomerEmail", MySecurity.Encrypt(UserEmail, true));
            _cookie.Values.Add("CustomerMobile", MySecurity.Encrypt(UserMobile, true));

            _cookie.Expires = DateTime.Now.AddDays(90);
            Response.Cookies.Add(_cookie);
        }
        catch (Exception Ex)
        {
            Ex = null;
        }
    }

    public string GetMotorBrand(string Brand)
    {
        string _strBrandClass = "gluaygluay";
        if (Brand == "AUDI")
        {
            _strBrandClass = "audi";
        }
        else if (Brand == "BMW")
        {
            _strBrandClass = "bmw";
        }
        else if (Brand == "CHER")
        {
            _strBrandClass = "chery";
        }
        else if (Brand == "CHEV")
        {
            _strBrandClass = "chevrolet";
        }
        else if (Brand == "CITR")
        {
            _strBrandClass = "citroen";
        }
        else if (Brand == "DAIH")
        {
            _strBrandClass = "daihatsu";
        }
        else if (Brand == "DFM")
        {
            _strBrandClass = "dfm";
        }
        else if (Brand == "FORD")
        {
            _strBrandClass = "ford";
        }
        else if (Brand == "HOND")
        {
            _strBrandClass = "honda";
        }
        else if (Brand == "HYUN")
        {
            _strBrandClass = "hyundai";
        }
        else if (Brand == "ISUZ")
        {
            _strBrandClass = "isuzu";
        }
        else if (Brand == "JAGU")
        {
            _strBrandClass = "jaguar";
        }
        else if (Brand == "JEEP")
        {
            _strBrandClass = "jeep";
        }
        else if (Brand == "KIA")
        {
            _strBrandClass = "kia";
        }
        else if (Brand == "LAND")
        {
            _strBrandClass = "landrover";
        }
        else if (Brand == "LEXU")
        {
            _strBrandClass = "lexus";
        }
        else if (Brand == "MAZD")
        {
            _strBrandClass = "mazda";
        }
        else if (Brand == "MERC")
        {
            _strBrandClass = "mercedes";
        }
        else if (Brand == "MINI")
        {
            _strBrandClass = "mini";
        }
        else if (Brand == "MITS")
        {
            _strBrandClass = "mitsubishi";
        }
        else if (Brand == "NISS")
        {
            _strBrandClass = "nissan";
        }
        else if (Brand == "PEUG")
        {
            _strBrandClass = "peugeot";
        }
        else if (Brand == "PORS")
        {
            _strBrandClass = "porsche";
        }
        else if (Brand == "PROT")
        {
            _strBrandClass = "proton";
        }
        else if (Brand == "SSAN")
        {
            _strBrandClass = "ssangyong";
        }
        else if (Brand == "SUBA")
        {
            _strBrandClass = "subaru";
        }
        else if (Brand == "SUZU")
        {
            _strBrandClass = "suzuki";
        }
        else if (Brand == "TATA")
        {
            _strBrandClass = "tata";
        }
        else if (Brand == "TOYO")
        {
            _strBrandClass = "toyota";
        }
        else if (Brand == "VOLK")
        {
            _strBrandClass = "volkswagen";
        }
        else if (Brand == "VOLV")
        {
            _strBrandClass = "volvo";
        }
        return _strBrandClass;
    }

    private void UpdateUserIdCarDetails(Int64 CarId, Int64 UserId, Int64 ExistingUserId, string ExistingEmail, string ChangeStatus, string Email, string Name, string Mobile)
    {
        try
        {
            Int64 _result = -1;
            MyDatabase _db = new MyDatabase();
            DataTable _dtResult = new DataTable();
            string _spName = "sprocCarDetailUpdateSingleItemByUserId";
            SortedList _sPara = new SortedList();
            _sPara.Add("@CarId", CarId);
            _sPara.Add("@RefCEUserId", UserId);
            _sPara.Add("@ExistingUserId", ExistingUserId);
            _sPara.Add("@ExistingEmail", ExistingEmail);
            _sPara.Add("@ChangeStatus", ChangeStatus);
            _sPara.Add("@Email", Email);
            _sPara.Add("@Name", Name);
            _sPara.Add("@Mobile", Mobile);

            _result = _db.ExecuteNonSqlSP(_spName, _sPara);
        }
        catch (Exception ex)
        {
        }
    }

    public Int32 CheckCallMeCount()
    {
        try
        {
            string CarId = "0";
            string UserId = "0";
            if (Session[CE.Global.General.CarId] != null)
            {
                CarId = Session[CE.Global.General.CarId].ToString();
            }
            if (Session[CE.Global.General.UserId] != null)
            {
                UserId = Session[CE.Global.General.UserId].ToString();
            }
            DataTable _dt = new DataTable();
            MyDatabase _db = new MyDatabase();
            string _sqlString = @"SELECT COUNT(*) RECORDCOUNT FROM tblContactUser WHERE ProductId = " + CarId + " AND RefCEUserId = " + UserId;
            _sqlString += " AND (CONVERT(VARCHAR(8),ModifiedDate,112) BETWEEN CONVERT(VARCHAR(8),DATEADD(DD, -60,dbo.fn_getUTCDateTime()),112) ";
            _sqlString += " AND CONVERT(VARCHAR(8),dbo.fn_getUTCDateTime(),112))";
            _dt = _db.GetDataTable(_sqlString);
            _db = null;

            string rtnCount = "0";
            Int32 _retResult = 0;
            if (_dt != null && _dt.Rows[0]["RECORDCOUNT"] != null)
            {
                rtnCount = _dt.Rows[0]["RECORDCOUNT"].ToString();
            }
            if (rtnCount != null)
            {
                if (!Int32.TryParse(rtnCount.ToString(), out _retResult))
                {
                    _retResult = 0;
                }
            }
            return _retResult;
        }
        catch (Exception ex)
        {
            return -1;
        }
    }

    protected void BKICalculationWithTimeout(long _carId, long _userId)
    {
        BKIDetailDB bki = new BKIDetailDB();

        System.Threading.Thread _thread = new System.Threading.Thread(() => bki.BKICalculation(_carId, _userId));
        _thread.Start();

        System.Diagnostics.Stopwatch _stopwatch = new System.Diagnostics.Stopwatch();
        _stopwatch.Start();

        bool _threadRunning = true;
        while (_threadRunning)
        {
            if (_thread.IsAlive)
            {
                if (_stopwatch.Elapsed.Seconds > 30)  //set timeout to 15 secounds at bki webservice >> (BKIDetailDB.cs)
                {
                    _thread.Abort();
                    _threadRunning = false;
                }
            }
            else
                _threadRunning = false;
        }
        _stopwatch.Stop();
    }

    private void GetPromotionDetails(Int64 CarId)
    {
        try
        {
            #region TrueYou Promotion
            hdnIsPromo.Value = "0";
            hdnPromoId.Value = "0";
            hdnPromoCode.Value = "0";
            string _TruePromo = CE.Global.General.GetUTCDateTime().ToString("yyyyMMdd");
            Int64 _intTruePromo = 0;
            Int16 IsTruePromo = 0;
            if (!Int64.TryParse(_TruePromo, out _intTruePromo))
            {
                _intTruePromo = 0;
            }
            if (Session["Language"] != null & Session["Language"].ToString() == "en-US")
            {
                if (_intTruePromo >= 20150814 && _intTruePromo <= 20151031)
                {
                    hdnIsPromo.Value = "1";
                    IsTruePromo = 1;
                }
            }
            else if (Session["Language"] != null & Session["Language"].ToString() == "th-TH")
            {
                if (_intTruePromo >= 25580814 && _intTruePromo <= 25581031)
                {
                    hdnIsPromo.Value = "1";
                    IsTruePromo = 1;
                }
            }
            if (IsTruePromo == 1)
            {
                this.Master.FindControl("hplNavCarInsuranceHeader").Visible = false;
                this.Master.FindControl("hplNavCarInsuranceSlider").Visible = false;
                MyDatabase _db = new MyDatabase();
                DataTable _dtResult = new DataTable();
                string _spName = "sprocGetPromoDetailsSelectedItem";
                SortedList _sPara = new SortedList();
                _sPara.Add("@CarId", CarId);
                _dtResult = _db.GetDataTableBySP(_spName, _sPara);
                if (_dtResult != null && _dtResult.Rows.Count > 0)
                {
                    Int16 PromoId = 0;
                    if (!Int16.TryParse(_dtResult.Rows[0]["Promotion"].ToString(), out PromoId))
                    {
                        PromoId = 0;
                    }
                    hdnPromoId.Value = PromoId.ToString();
                    hdnPromoCode.Value = _dtResult.Rows[0]["PromoCode"].ToString();
                }
            }
            #endregion
        }
        catch (Exception ex)
        {
        }
    }

    private Int32 GetBuyInsuranceCount(Int64 RefCEUserId)
    {
        try
        {
            Int32 _intSalesCount = 0;
            MyDatabase _db = new MyDatabase();
            DataTable _dtResult = new DataTable();
            string _spName = "sprocGetCustomerPromoInsuranceCountSelectedItem";
            SortedList _sPara = new SortedList();
            _sPara.Add("@RefCEUserId", RefCEUserId);
            _dtResult = _db.GetDataTableBySP(_spName, _sPara);
            if (_dtResult != null && _dtResult.Rows.Count > 0)
            {
                if (!Int32.TryParse(_dtResult.Rows[0]["SalesCount"].ToString(), out _intSalesCount))
                {
                    _intSalesCount = 0;
                }
            }
            return _intSalesCount;
        }
        catch (Exception ex)
        {
            return -1;
        }
    }

}
